简体   繁体   中英

Python loop not breaking out

I expect the whole loop to exit when my isQuit variable is "yes" and customer becomes False . However, the current loop seems to be repeated until the order_item is in menu_items .

Can you please help me change my code so that the loops stop when the user wants to quit?

def order(menu):
    FISH_CHIPS_PRICES = menu
    menu_items = []

    for item in FISH_CHIPS_PRICES:
        menu_items.append(item.lower())

    orders = []
    customer = True
    while customer:
        orders.append({})

        for item in FISH_CHIPS_PRICES:
           orders[-1][item] = 0

        while True:
            while True:
                order_item = input("What do you want to buy?")
                if order_item.lower() not in menu_items:
                    print("Item:", order_item, "not available")
                    isQuit = input("Do you want to quit: yes / no:")
                    if isQuit == "yes":
                        customer = False
                else:
                    break

You're seeing this behavior because of the two infinite while loops enclosing to your isQuit variable. break ing out of a loop only stops the immediately enclosing loop.

One possible solution is to immediately return when isQuit is "yes" , which will exit the entire order() function.

# ...
isQuit = input("Do you want to quit: yes / no:")
if isQuit == "yes":
    return

Another possible solution is to remove the outer infinite while loop since it does not seem to serve any function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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