首页 > 解决方案 > 跳出while循环

问题描述

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

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

标签: pythonpython-3.xwhile-loop

解决方案


似乎您有布尔值openMenu,并且仅在 if 中输入了 while 循环openMenu = True

因此,解决此问题的一种方法是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 中的所有元素。


推荐阅读