找出除了 ValueError

跟随 Al Sweigarts python 课程并尝试修改他的 cat 代码一些。我可以只使用 if 和 elif 语句输入“除了 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')

如果输入无效数字,我希望代码重复,同时在非整数值后重复。不过,我无法通过除了 ValueError 部分。谢谢!


www说
浏览 211回答 1
1回答

白猪掌柜的

一个except块需要一个try块。您会在try块内找到异常,如果找到,except则运行子句。while True:&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; print('How many cats do you got: ')&nbsp; &nbsp; &nbsp; &nbsp; numCats = int(input())&nbsp; &nbsp; &nbsp; &nbsp; if numCats >= 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('That was not a valid number')&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; print('That was not a valid number')if numCats >= 4:&nbsp; &nbsp; print('That is a lot of cats')elif numCats < 4:&nbsp; &nbsp; print('That is not a lot of cats')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python