如何退出while循环

时间:2019-12-08 10:09:12

标签: python loops while-loop

我不明白为什么我不能从简单循环中走出来。

代码如下:

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")

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这应该可以解决您的问题:

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")

以下情况

if b == '0':
    a = 0

应该与if b:条件处于同一范围。

答案 1 :(得分:0)

您可以在每个循环分支的结尾处t break out of the loop because. actually, there is no中断. You need to put break`命令,在该分支中,您想停止循环以退出循环。

此外,您可以分配a = 0而不是break