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

Python布尔函数调用的if条件恒为True及评分程序异常修复求助

问题2:用户评分代码运行异常,输入非数字时抛出ValueError,如何修改?

看了你的代码,问题根源和第一个问题完全一样:你写了if RR.isnumeric而不是if RR.isnumeric(),导致这个条件永远为True,不管输入什么都会进入分支执行int(RR)。当输入非数字(比如'g')时,自然就会抛出ValueError了。另外你的代码还漏了对0、6这类无效数字的处理,我一起帮你补上了。

这里是修改后的完整代码,还做了点小优化:

while True:
    RR = input("What would you rate this program(?/5): ")
    if RR.isnumeric():  # 关键修复:加括号调用方法,正确判断是否为数字字符串
        rating = int(RR)
        if rating == 5:
            print("Looks like you are highly satisfied with this program :D")
            break
        elif 3 <= rating <= 4:
            print(f"Ohh! Next time I'll try my best to change this '{rating}' into 5 ;D")
            break
        elif 1 <= rating <= 2:
            print("I am sorry if I wasn't good, I'll try my best next time :|")
            break
        else:
            # 处理0、6及以上的无效数字输入
            print("Invalid Rating, Try again...")
            continue
    else:
        # 非数字输入直接提示,避免进入int转换步骤
        print("Invalid input! Please enter a number between 1 and 5.")
        continue

主要修改说明:

  1. 修复isnumeric的调用方式,现在能准确判断输入是否为数字;
  2. 把非数字输入的处理单独放在else分支,彻底避开int转换的报错;
  3. 优化条件判断写法(比如3 <= rating <=4比rating ==4 or rating ==3更简洁易读);
  4. 补充了对0或大于5的数字输入的处理,覆盖所有无效场景。

这样修改后,不管用户输入非数字还是无效数字,都会友好提示并继续循环,再也不会报错啦。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:56:13