我正在学习Python课程的自动化内容,其中一个课程让我很困惑,关于try: and以外:子句的用法。
当我运行下面的课程中描述的代码时,使用if/one语句工作,因为执行了text子句,python在输入'one‘这样的文本时打印’您没有输入一个数字‘
print('how many cats do you have?')
numcats=input()
try:
if int(numcats)>=4:
print('that is a lot of cats')
else:
print('that is not many cats')
except ValueError:
print('you did not enter a number')但是,当我按照本例使用elif语句时,不会执行get子句,并且会得到一个错误。在我看来,他们俩看起来都应该产生同样的结果。
我遗漏了什么?
print('how many cats do you own?')
numcats=int(input())
try:
if numcats<=5 and numcats>0:
print('that is not alot of cats')
elif numcats >5 and numcats<=10:
print('that is alot of cats! more than five and less than 10!')
elif numcats <0:
print('you cant have less than zero cats!')
elif numcats>10:
print('more than 10 cats! thats crazy!')
except ValueError:
print('you did not enter a numerical value, try again')我比较了这两组代码的结构,看起来它们应该产生相同的结果,不知道为什么elif语句会导致not :子句不被执行?我以为这和如果,否则的声明是一样的
发布于 2022-11-03 10:56:20
产生ValueError的东西是将输入转换为整数(int(numcats)和int(input()))。在第一个示例中,您在try块中执行try之前的第二个步骤,因此错误不会被捕获。
将numcats=int(input())移动到try块中,这应该很好。
发布于 2022-11-03 11:01:12
您需要将int()转换放在try:块中。
就像这样:
while True:
try:
numcats = int(input('how many cats do you own? '))
break
except ValueError:
print('you did not enter a numerical value, try again')
if numcats <= 5 and numcats > 0:
print('that is not alot of cats')
elif numcats > 5 and numcats <= 10:
print('that is alot of cats! more than five and less than 10!')
elif numcats < 0:
print('you cant have less than zero cats!')
elif numcats > 10:
print('more than 10 cats! thats crazy!')发布于 2022-11-03 10:59:52
试一试:
print('how many cats do you own?')
numcats=input()
try:
if int(numcats)<=5 and int(numcats)>0:
print('that is not alot of cats')
elif int(numcats) >5 and int(numcats)<=10:
print('that is alot of cats! more than five and less than 10!')
elif int(numcats) <0:
print('you cant have less than zero cats!')
elif int(numcats)>10:
print('more than 10 cats! thats crazy!')
except ValueError:
print('you did not enter a numerical value, try again')https://stackoverflow.com/questions/74301916
复制相似问题