#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])
答案 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"})
请注意:
n
和valid_colours
是参数,使代码更灵活,可重复使用; valid_colours
是set
,这使得成员资格测试(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']