简体   繁体   English

跳出 while 循环

[英]Breaking out of while loop

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

I want to break out the loop after the customer chooses one of these options我想在客户选择其中一个选项后打破循环

It seems you have the boolean openMenu and the while loop is only entered if openMenu = True .看来您有 boolean openMenu并且只有在openMenu = True时才进入 while 循环。

Therefore, one way to solve this is to set openMenu = False after each of the conditional statements.因此,解决这个问题的一种方法是在每个条件语句之后设置openMenu = False

You would have:你将会拥有:

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

However, it doesn't seem like you really need the while loop since your for loop iterates over all the elements in your shoppingList.但是,您似乎并不真的需要 while 循环,因为您的 for 循环遍历了 shoppingList 中的所有元素。

I really didn't understand your question.我真的不明白你的问题。 If you want to break from the while loop, when certain condition is met, use 'break' statement.如果你想从 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM