跟随 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 部分。谢谢!
1 回答

白猪掌柜的
TA贡献1893条经验 获得超10个赞
一个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')
添加回答
举报
0/150
提交
取消