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

如何用Exceptions评估用户输入?范围校验循环失效问题求助

问题修复:输入超出范围时无法循环要求重新输入

你的代码核心问题是覆盖了原本存储提示信息的self.prompt变量:第一次输入后,你把self.prompt从字符串改成了整数,后续循环调用input(self.prompt)时,input函数需要传入字符串参数,传入整数会直接报错,导致程序无法正常循环。

同时你的代码还存在几个不符合需求的地方:提示信息和需求不一致、没有返回有效数值、异常捕获范围太宽泛。

以下是修改后的完整代码:

class Num_Evaluation:
    def __init__(self, prompt, min_val, max_val):
        # 避免使用min、max作为变量名(它们是Python内置函数)
        self.prompt = prompt
        self.min_val = min_val
        self.max_val = max_val

    def num_check(self):
        while True:
            try:
                # 用临时变量存储输入,不要覆盖提示字符串
                user_input = int(input(self.prompt))
                # 直接判断范围,替代assert(assert一般用于调试,不适合业务逻辑)
                if self.min_val <= user_input <= self.max_val:
                    print('The number is :', user_input)
                    return user_input
                else:
                    # 输出需求指定的范围错误提示,替换占位符为实际数值
                    print(f'error: the value is not within permitted range ({self.min_val}..{self.max_val})')
            except ValueError:
                # 捕获特定的数值转换异常,避免捕获所有异常
                print('Error: wrong input')

# 实例化并调用
user1 = Num_Evaluation("enter number in range -10 to 10: ", -10, 10)
print(user1.num_check())

关键修改点说明:

  • 变量名优化:把min、max改成min_val、max_val,避免和Python内置函数冲突。
  • 保留提示字符串:使用临时变量user_input存储用户输入,不会覆盖self.prompt,确保循环时提示信息正常显示。
  • 范围判断:用if替代assert,更适合业务逻辑判断,避免断言被禁用的问题。
  • 异常处理:只捕获ValueError(非整数输入时抛出的异常),避免捕获所有异常导致隐藏其他问题。
  • 符合需求提示:输出的错误信息完全匹配需求描述。
  • 返回有效数值:添加return user_input,确保方法返回符合要求的数值。

内容的提问来源于stack exchange,提问作者Mckinnon T Chinowe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:17:19