You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python初学者求助:输入Quit时Code1报错,求解析原因

问题分析:输入"Quit"时Code1报错的原因

核心问题出在代码的执行顺序上:

Code1的问题

当你输入"Quit"时,程序会先执行第一个判断条件里的int(inp)——也就是尝试把字符串"Quit"转换成整数。但"Quit"根本不是合法的数字格式,这一步直接就会抛出ValueError,程序还没来得及走到elif inp=="Quit"的分支就崩溃了。

Code1代码:

inp=input("Enter the number between 5 to 9:")

if (int(inp)<=5 or int(inp)>=9):
   raise ValueError ("Number should be between 5 to 9")

elif inp=="Quit":
  print("You Quit")

Code2为什么正常

Code2调整了判断顺序,先检查输入是否是"Quit":如果是,直接执行打印逻辑,完全不会触发后面的int(inp)转换操作,自然不会出现类型转换错误。

Code2代码:

inp = input("Enter any value between 5 and 9 : ")

if inp == "Quit":
    print("You Quit")
elif (int(inp) <= 5 or int(inp) >=9):
    raise ValueError("Value should be between 5 and 9")

简单来说,要先处理非数字的特殊输入,再去做数字相关的转换和判断,避免非法转换导致的报错。

内容的提问来源于stack exchange,提问作者Jigyesh Pareek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 13:49:54