如何打破这个循环? (Python)

时间:2021-04-06 18:57:47

标签: python loops break

    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'时,它会说“你可以吃水果”,但“你做了一个无效的选择。请再次选择:”再次。

当我输入列表中的水果时,如何让这个循环停止?当我把“break”放在代码的末尾时,它说它是一个无效的语法..

4 个答案:

答案 0 :(得分:3)

使用 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')

答案 1 :(得分:2)

这行得通:

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')

答案 2 :(得分:1)

试试这个。假设您需要使用 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: ')

答案 3 :(得分:1)

我不知道这是否是您的实际代码问题的格式。你有些语法错误:

  • 在每个 ifelse 的末尾,您需要像使用 : 条件一样使用 while
  • 您必须使用正确的缩进。

一旦您修复了这些错误,请检查您想要满足的条件,以便使用 break 跳出循环。

相关问题