[英]How to break this loop? (python)
available_fruits = ['apple', 'grape', 'banana']
choice = input('Please pick a fruit I have available: ')
while True : choice= input('You made an invalid choice. Please pick again:')
if choice not in available_fruits
else print('You can have the fruit')
当用户在列表“available_fruits”中输入内容时,我想让这个循环停止。 但是当我输入“苹果”时,它会说“你可以吃水果”,但又会说“你做了一个无效的选择。请再选一次:”。
当我输入列表中的水果时,如何使这个循环停止? 当我把“break”放在代码的末尾时,它说它的语法无效..
使用 while 条件而不是只是 while True,这样的工作:
available_fruits = ['apple', 'grape', 'banana']
choice = input('Please pick a fruit I have available: ')
while choice not in available_fruits:
choice= input('You made an invalid choice. Please pick again:')
print('You can have the fruit')
这会起作用:
available_fruits = ['apple', 'grape', 'banana']
choice = input('Please pick a fruit I have available: ')
while True:
if choice in available_fruits:
print('You can have the fruit')
break
else:
choice = input('You made an invalid choice. Please pick again: ')
但总的来说,我建议您创建具有实际条件的 while 循环。 这就是while循环的用途。 当条件评估为 False 时,它们会自动中断。 也干净多了。
例子:
available_fruits = ['apple', 'grape', 'banana']
choice = input('Please pick a fruit I have available: ')
while choice not in available_fruits:
choice = input('You made an invalid choice. Please pick again: ')
print('You can have the fruit')
试试这个。 假设你需要使用break。
available_fruits = ['apple', 'grape', 'banana']
choice = input('choose a fruit: ')
while True :
if choice in available_fruits:
print('you picked a valid fruit')
break
else:
choice = input('choose a fruit: ')
我不知道它是否是您的问题的格式,即这是否是您的实际代码。 你有些有语法错误:
if
或else
结束时,您需要使用:
,就像使用while
条件一样。 修复这些错误后,请检查您想要满足的条件,以便使用break
退出循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.