跟随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部分。谢谢!
答案 0 :(得分:0)
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')