如何修改我的代码,以便用户可以输入相同的颜色四次,但不能输入我的列表范围之外的任何颜色?

时间:2014-11-28 23:37:18

标签: python python-3.x

#Colours

colourRange = ["red", "green", "blue","yellow", "magenta","cyan"]
print("Please enter colours from: ", colourRange)
colour1 = input("Please press Enter after you have entered your colour\n\
Enter your 1st colour?: ")
colour2 = input("Enter 2nd colour?: ")
colour3 = input("Enter 3rd colour?: ")
colour4 = input("Enter 4th colour?: ")
colour = [colour1,colour2,colour3,colour4]

#loop for four colour choice within list     

for i in range(4):
    while colour[i] not in colourRange:
        print(colour[i], "is not a valid colour, please \
            select another from :  ", colourRange)
        colour[i] = (input("Replace with: "))
    else:
        colourRange.remove(colour[i])

1 个答案:

答案 0 :(得分:0)

如果您编写一个函数来获取一个有效颜色,然后多次调用它,更简单

def get_colour(prompt, valid_colours):
    """Allow the user to enter a single valid colour."""
    while True:
        colour = input(prompt)
        if colour in valid_colours:
            return colour
        print("Not a valid colour.")

def get_colours(n, valid_colours):
    """Get n valid colours from the user."""
    return [get_colour("Input colour {}: ".format(i+1), valid_colours) 
            for i in range(n)]

colours = get_colours(4, {"red", "green", "blue", "yellow", "magenta", "cyan"})

请注意:

  • nvalid_colours是参数,使代码更灵活,可重复使用;
  • 我使用list comprehension来简化代码;
  • valid_coloursset,这使得成员资格测试(colour in valid_colours)的速度更快(O(1)O(n)对于元组或列表);和
  • 我使用str.format而不是连接+

使用中:

>>> colours = get_colours(4, {"red", "green", "blue", "yellow", "magenta", "cyan"})
Input colour 1: purple
Not a valid colour.
Input colour 1: cyan
Input colour 2: green
Input colour 3: yellow
Input colour 4: red
>>> colours
['cyan', 'green', 'yellow', 'red']