【问题标题】:Breaking out of while loop跳出while循环
【发布时间】:2020-10-09 22:30:28
【问题描述】:
shoppingList = [('Carrot',2), ('Onion',1), ('Tomato',3)]
amountGiven = 12
for item, price in shoppingList:

    openMenu = True
    while openMenu:
        costumerPick = input('Please choose item from the shoppingList\n')

        if costumerPick == 'Carrot':
            print('That would be: ${}'.format(price))
            amountGiven = amountGiven - price

            
        elif costumerPick == 'Onion':
            print('That would be: ${}'.format(price))
            amountGiven = amountGiven -price
            
        elif costumerPick == 'Tomato':
            print('That would be: ${}'.format(price))
            amountGiven = amountGiven - price

我想在客户选择这些选项之一后打破循环

【问题讨论】:

  • 鉴于您的问题的标题,您显然知道break 是打破循环的方法。所以,既然你已经知道如何去做你所问的——你的真正问题是什么?
  • 我们希望您在此处发布之前进行适当的研究,例如搜索您的问题标题。请参阅任何有关循环的教程;注意break 声明。
  • 我的问题是我应该在哪里使用 break 命令来结束循环?

标签: python python-3.x while-loop


【解决方案1】:

您似乎有布尔值openMenu,并且只有在openMenu = True 时才进入while 循环。

因此,解决此问题的一种方法是在每个条件语句之后设置openMenu = False。

你会:

openMenu = True
    while openMenu:
        costumerPick = input('Please choose item from the shoppingList\n')

        if costumerPick == 'Carrot':
            print('That would be: ${}'.format(price))
            amountGiven = amountGiven - price
            openMenu = False

            
        elif costumerPick == 'Onion':
            print('That would be: ${}'.format(price))
            amountGiven = amountGiven -price
            openMenu = False
            
        elif costumerPick == 'Tomato':
            print('That would be: ${}'.format(price))
            amountGiven = amountGiven - price
            openMenu = False

但是,您似乎并不真的需要 while 循环,因为您的 for 循环会遍历您的 shoppingList 中的所有元素。

【讨论】:

  • 一开始有for循环的东西,我尝试了所有这些情况,它没有工作。我认为你是对的 for 循环就足够了
  • 太好了,如果这是您要使用的解决方案,请指出这是公认的解决方案!
【解决方案2】:

我真的不明白你的问题。如果你想从while循环中中断,当满足某些条件时,使用'break'语句。

shoppingList = [('Carrot',2), ('Onion',1), ('Tomato',3)]
amountGiven = 12

for item, price in shoppingList:
    openMenu = True
    while openMenu:
        costumerPick = input('Please choose item from the shoppingList\n')

        if costumerPick == 'Carrot':
            print('That would be: ${}'.format(price))
            amountGiven = amountGiven - price
            break

        elif costumerPick == 'Onion':
            print('That would be: ${}'.format(price))
            amountGiven = amountGiven -price
            break
        
        elif costumerPick == 'Tomato':
            print('That would be: ${}'.format(price))
            amountGiven = amountGiven - price
            break

【讨论】:

  • 说意外缩进!
  • @user14363840:我编辑了答案以遵循正确的缩进。 Python 是基于缩进的语言。请阅读 Python 语言中的缩进。
  • @user14363840:如果我的回答或 slumpyrat 的回答解决了您的问题,请接受相应的回答。它对其他人有用。
猜你喜欢
  • 2021-08-31
  • 2015-04-08
  • 2020-01-03
  • 2013-05-06
  • 1970-01-01
  • 1970-01-01
  • 2012-08-25
  • 2020-04-17
  • 2021-08-14
相关资源
最近更新 更多