首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >试一试:除了:不适用于elif语句的子句?

试一试:除了:不适用于elif语句的子句?
EN

Stack Overflow用户
提问于 2022-11-03 10:53:52
回答 4查看 47关注 0票数 0

我正在学习Python课程的自动化内容,其中一个课程让我很困惑,关于try: and以外:子句的用法。

当我运行下面的课程中描述的代码时,使用if/one语句工作,因为执行了text子句,python在输入'one‘这样的文本时打印’您没有输入一个数字‘

代码语言:javascript
运行
复制
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子句,并且会得到一个错误。在我看来,他们俩看起来都应该产生同样的结果。

我遗漏了什么?

代码语言:javascript
运行
复制
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 :子句不被执行?我以为这和如果,否则的声明是一样的

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2022-11-03 10:56:20

产生ValueError的东西是将输入转换为整数(int(numcats)int(input()))。在第一个示例中,您在try块中执行try之前的第二个步骤,因此错误不会被捕获。

numcats=int(input())移动到try块中,这应该很好。

票数 3
EN

Stack Overflow用户

发布于 2022-11-03 11:01:12

您需要将int()转换放在try:块中。

就像这样:

代码语言:javascript
运行
复制
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!')
票数 1
EN

Stack Overflow用户

发布于 2022-11-03 10:59:52

试一试:

代码语言:javascript
运行
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74301916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档