>>> colours = []
>>> prompt ='Enter another one of your favourite colours ( type return to end):'
>>> colour = input(prompt)
Enter another one of your favourite colours(type return to end): blue
>>> colour
'blue'
>>> colours
[]
>>> while colour != ' ' :
colours.append(colour)
colour = input(prompt)
Enter another one of your favourite colours ( type return to end): yellow
Enter another one of your favourite colours ( type return to end): brown
Enter another one of your favourite colours ( type return to end): return
我正在使用 Python 3
这里我将用户在提示时输入的颜色添加到颜色 [] 列表中,问题是我无法退出此循环。请帮助我。
我知道我们可以只使用 ctrl+c 但它是一个键盘中断所以我不想使用它。
P.S - 我刚开始学习 python,如果它看起来像一个愚蠢的问题,请不要介意。
请您参考如下方法:
您的 while 条件与您期望的用户输入不匹配。如果您希望循环在用户输入文字字符串 "return" 时退出,那么您应该使用:
while colour != 'return':
如果您希望循环在用户按下 Return 键时停止,请使用空的 '':
while colour != '':
鉴于这种歧义,您还可以使用 in 将两者结合起来,并且还可以strip 输入以考虑可能的空格:
while colour.strip() not in ('return', ''):
