简体   繁体   中英

How to exit while loop

I don't understand why I cannot go out from simple loop.

Here is the code:

a = 1

#tip checking loop
while a != 0:
    # tip value question - not defined as integer to be able to get empty value
    b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
    # loop checking if value has been given
    if b:
        #if b is given - checking how much it is
        if int(b) >= 100:
            print("\nJohnny says : SUPER!")
        elif int(b) < 100:
            print("\nJohnny says : Next time I spit in your soup")
    elif b == '0':
        a = 0

    else:
        print("You need to tell how much you tipped")

print("\n\nZERO ? this is the end of this conversation")

Thanks for your help.

This should solve your problem:

a = 1

#tip checking loop
while a != 0:
    # tip value question - not defined as integer to be able to get empty value
    b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
    # loop checking if value has been given
    if b:
        #if b is given - checking how much it is
        if int(b) >= 100:
            print("\nJohnny says : SUPER!")
        elif int(b) < 100:
            print("\nJohnny says : Next time I spit in your soup")
        if b == '0':
            a = 0

    else:
        print("You need to tell how much you tipped")

print("\n\nZERO ? this is the end of this conversation")

the following condition

if b == '0':
    a = 0

should be in the same scope as the if b: condition.

You can t break out of the loop because. actually, there is no t break out of the loop because. actually, there is no break . You need to put . You need to put break` command at the end of every loop branch where you would like to stop looping in order to break out of the loop.

Also, you could break out assigning a = 0 instead of the break .

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