退出写在 python shell 中的 运行 while 循环
Exit a running while loop written in the python shell
>>> 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', ''):
>>> 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', ''):