如何打破这个循环?(python)
当用户输入列表中可用的内容时,我想让这个循环停止。 但当我进入“苹果”时,它说你可以吃水果,但你做了一个无效的选择。请再挑一次:再挑一次如何打破这个循环?(python),python,loops,break,Python,Loops,Break,当用户输入列表中可用的内容时,我想让这个循环停止。 但当我进入“苹果”时,它说你可以吃水果,但你做了一个无效的选择。请再挑一次:再挑一次 当我输入列表中的水果时,如何使循环停止?当我在代码末尾加上分隔符时,它表示这是一种无效语法。使用while条件而不是while True, 类似这样的工作原理: available_fruits = ['apple', 'grape', 'banana'] choice = input('Please pick a fruit I h
当我输入列表中的水果时,如何使循环停止?当我在代码末尾加上分隔符时,它表示这是一种无效语法。使用while条件而不是while True, 类似这样的工作原理:
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 = ['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')
但一般来说,我建议您根据实际情况创建while循环。这就是while循环的用途。当条件计算为False时,它们会自动中断。它也干净多了
例如:
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: ')
试试这个。假设您需要使用break
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')
我不知道这是否是你的问题的格式,如果这是你的实际代码。您有一些语法错误: 在每个if或else结束时,您需要使用:正如您在while条件中所做的那样。 您必须使用正确的缩进。
一旦修复了这些错误,请检查您想要满足的条件,以便通过break退出循环。该代码不是有效的Python,缩进很重要。请提取a并将其作为问题的一部分提供,这样人们就不必猜测导致问题的代码是什么。作为一个新用户,也需要阅读。这仍然会抱怨在循环的第一次迭代中做出了无效的选择。谢谢,你说得对:我编辑了代码。
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: ')