While循环会打印大量消息

时间:2020-05-06 18:53:56

标签: python-3.x

我的代码要求用户输入一个数字,如果该数字是整数并且小于20,则完成输入;如果不是,则应打印“错误,请重试”,让我们重试,但不只是它吓坏了,打印出无止境的消息

good1 = False
while not good1:
    storage = input("A number")
    try:
        int(storage)
        good1 = True
        good2 = False
        while not good2:
            if int(storage) > 20:
                print("Error, try again.")
            else:
                print("--")
    except ValueError:
        print("Error, try again.")

3 个答案:

答案 0 :(得分:1)

您从未更改过good2的值,因此它始终是真实的,并且会继续打印。

尝试突破内循环。另外,请注意,您已经将good1设置为True,所以即使它大于20现在也很好,如果它大于20,则需要将其设置为False使程序再次要求输入新号码。代码应该像这样

good1 = False
while not good1:
    storage = input("A number")
    try:
        int(storage)
        good1 = True
        good2 = False
        while not good2:
            if int(storage) > 20:
                print("Error, try again.")
                good1 = False
            else:
                print("--")
                good2 = True;
            break
        if good2:
            break
    except ValueError:
        print("Error, try again.") 

答案 1 :(得分:1)

您可能正在寻找这样的东西:

good_number = False

while not good_number:
    storage = input("A number")
    try:
        if int(storage) > 20:
            print("Error, try again.")
        else:
            print("--")
            good_number = True
    except ValueError:
        print("Error, try again.")

答案 2 :(得分:0)

那是因为你有

while not good2:

这将永远持续下去。因为您基本上说的是true,所以请检查int是否> =20。如果是,则发布错误,否则发布“-”。然后,if语句继续运行,因为good2从未更改为false(或者,由于NOT2而不是true)

相关问题