弄清楚 ValueError 除外

Figuring out except ValueError

跟随 Al Sweigarts python 的课程并尝试修改他的猫代码一些。我可以仅使用 if 和 elif 语句输入 "except ValueError",但我认为使用 while 语句我搞砸了。我希望这个简单的代码在用户输入错误的东西时重复,到目前为止它是有效的。我只需要输入一些可以解决非整数的内容作为输入。

是否与未使用 break/continue 语句有关?

print('How many cats do you got')
numCats = int(input())

while numCats < 0:
    print('That is not a valid number')
    print('How many cats do you got')
    numCats = int(input())

if numCats >= 4:
        print('That is a lot of cats')

elif numCats < 4:
    print('That is not a lot of cats')

except ValueError:
    print('That was not a valid number')

我只想在输入无效数字时重复代码,同时在非整数值后重复。我无法通过 except ValueError 部分。谢谢!

一个except块需要一个try块。您在 try 块中找到异常,如果发现 except 子句是 运行.

while True:
    try:        
        print('How many cats do you got: ')
        numCats = int(input())
        if numCats >= 0:
            break
        else:
            print('That was not a valid number')
    except ValueError:
        print('That was not a valid number')

if numCats >= 4:
    print('That is a lot of cats')

elif numCats < 4:
    print('That is not a lot of cats')