Python程序输入校验问题:如何处理非数字输入并提示错误?
解决Python输入非数字时的报错问题
嘿,刚入门Python遇到这种输入校验的问题完全正常!你的原代码在输入数字时逻辑没问题,但因为直接把输入转成整数,一旦输入字母或其他非数字字符就会触发ValueError报错。咱们可以用两种实用的方式解决这个问题:
你的原代码:
i = input("input weight = ") def chicken(i): price = 2000 print('price /kg = ',price) totalprice = int(i)*price print('total price = ',totalprice) chicken(i)
方法1:用try-except捕获异常(推荐新手使用)
这是Python处理这类错误最常用的方案,核心思路是「尝试执行可能出错的代码,出错时就执行错误处理逻辑」:
i = input("input weight = ") def chicken(weight_input): price_per_kg = 2000 print('price /kg = ', price_per_kg) try: # 尝试将输入转换为整数 weight = int(weight_input) total_price = weight * price_per_kg print('total price = ', total_price) except ValueError: # 转换失败(输入非数字)时执行这里 print("wrong character") chicken(i)
小细节说明:
- 我把变量名改成了更有意义的
price_per_kg、weight_input,比原代码的price、i可读性更强,新手尽早养成好的命名习惯会受益良多~ try块包裹了可能抛出异常的代码(也就是把输入转成int的操作),如果转换成功就正常计算总价;如果失败(比如输入了字母),就会跳到except ValueError块,打印你需要的错误提示。
方法2:先判断输入是否为纯数字
如果你不想用异常捕获,也可以先检查输入是否是全数字字符:
i = input("input weight = ") def chicken(weight_input): price_per_kg = 2000 print('price /kg = ', price_per_kg) # 检查输入是否是纯正数字符(注意:不支持负数和小数) if weight_input.isdigit(): weight = int(weight_input) total_price = weight * price_per_kg print('total price = ', total_price) else: print("wrong character") chicken(i)
注意事项:
isdigit()方法只能识别纯正整数的字符,如果你的场景需要支持小数(比如输入1.5公斤),还是推荐用第一种try-except的方式(把int换成float即可),因为判断小数的逻辑会复杂很多。
内容的提问来源于stack exchange,提问作者aryo suatmodjo
相关产品推荐
相关产品推荐

