我如何再次运行此脚本并避免无限循环? [重复]

问题描述 投票:0回答:4

这里是python noob。

当用户触发elif子句时,出现无限循环。如何使程序再次询问原始问题?

print('How many cats do you have?')

numCats = input()


def cats():

    try:

        while True:
            if int(numCats) >= 4:
                print("That's a lot of cats!")
                break

            elif int(numCats) < 0:
                print("Please a number enter that is 0 or greater")


            else:
                print("That's not a lot of cats")
                break      

    except ValueError:
        print("You did not enter a number")

cats()
python loops infinite
4个回答
0
投票

numCats = input()之后的elif处输入print("Please a number enter that is 0 or greater")


0
投票

尝试如下更改省略号:

elif int(numCats) < 0:
    numCats = input("Please a number enter that is 0 or greater")

0
投票

您需要在elif语句后添加break。那将使您的代码停止运行。或者,您可以再次提出输入问题。像这样的东西:

def cats():
    try:
        while True:
            if int(numCats) >= 4:
                print("That's a lot of cats!")
                break

            elif int(numCats) < 0:
                print("Please a number enter that is 0 or greater")
                print('How many cats do you have?')
                numCats = input()
                cats()

            else:
                print("That's not a lot of cats")
                break      
    except ValueError:
        print("You did not enter a number")

0
投票

像这样编辑elif

elif int(numCats) < 0:
    print("Please a number enter that is 0 or greater")
    numCats = input('How many cats do you have?')
© www.soinside.com 2019 - 2024. All rights reserved.