Python中自定义catch_error_str函数无法捕获数字输入异常的问题
自定义输入校验函数失效的原因与修复方法
核心问题原因
- 存在一个小认知误会:
input()函数从终端读取到的内容本身就是字符串类型,额外用str()对返回值做转换的操作永远不会触发ValueError异常。 - 原try代码块内没有任何可能抛出类型错误的逻辑,因此只要进入try分支,不管输入的是数字、字母还是特殊字符,都会直接将校验标记
unvalid设为False并返回内容,完全触发不了错误提示的分支。
举个实际执行的例子:当你输入"2"时,程序的执行路径是:读取输入得到字符串"2"-> 调用str("2")得到同样的字符串"2"-> 全程没有报错,直接返回结果。整个流程根本走不到except ValueError的错误提示里。
修复思路
我们想实现的校验规则是“输入内容不能包含数字”,这个规则不会在类型转换的时候自动抛出异常,必须主动逐字符检查输入内容是否符合规则,而不是套空的try块等待异常触发。
可直接运行的修正代码
def catch_error_str(): unvalid = True while unvalid: input_content = input().strip() # 检查输入是否包含数字字符 if any(char.isdigit() for char in input_content): print("You must not enter any numbers, please try again:") continue # 补个空值校验,避免用户直接回车提交空内容 if not input_content: print("Input cannot be empty, please try again:") continue unvalid = False return input_content def surname(): print("What is the surname of the lead booker ") last_name = catch_error_str() print(last_name) print("Welcome to Copington Adventure Theme Park's automated ticket system\nplease press any button to see the ticket prices.") enter = input() print("\nAdult tickets are £20 each \nChild tickets are £12 each \nSenior citizen tickets are £11 each") surname()
修正后的逻辑说明
- 拿到输入后先去掉首尾多余的空格,避免无效的空格内容通过校验
- 逐字符检查输入内容,只要任意位置出现数字字符,就弹出提示让用户重新输入
- 增加空值校验,避免用户直接按回车得到无效的空姓氏
- 只有输入完全符合规则(无数字、非空),才会把内容返回给后续流程使用
内容的提问来源于stack exchange,提问作者archana kumari
相关产品推荐
相关产品推荐

