如何限制Python的input()函数仅接收整数和浮点数输入?
问题根因
- 初始代码错误点:
- 类型判断逻辑无效:
type(weight) == float or int写法不符合Python语法规则,实际执行等价于(type(weight) == float) or (int),而int作为内置对象在布尔判断中永远为真,因此循环条件始终成立 - 未做类型转换:Python 3中
input()函数默认返回字符串类型,直接和数字做大小比较必然触发类型不兼容报错
- 类型判断逻辑无效:
- 直接转float的代码缺陷:没有处理输入非数字场景下的转换异常,会直接抛出
ValueError终止程序
解决思路
使用try-except异常捕获机制处理不确定输入的类型转换,这是Python中处理这类场景的标准方案,逻辑如下:
- 先获取用户输入的原始字符串
- 尝试把输入转换为float类型
- 转换成功则进入运费计算逻辑
- 转换失败则输出
Invalid input
可用代码示例
weight_input = input("How heavy is the package you want to ship? ") try: weight = float(weight_input) if weight <= 2: price_per_pound = 1.50 elif weight <= 6: price_per_pound = 3.00 else: price_per_pound = 4.00 # 可按需添加总运费计算输出逻辑,示例:print(f"Total shipping cost: ${weight * price_per_pound:.2f}") print(f"Shipping cost per pound: ${price_per_pound:.2f}") except ValueError: print("Invalid input")
扩展优化(输入错误后可重复输入)
如果需要用户输入错误后不用重启程序即可重新输入,可添加循环逻辑:
while True: weight_input = input("How heavy is the package you want to ship? ") try: weight = float(weight_input) break except ValueError: print("Invalid input, please enter a valid number") # 运费计算逻辑 if weight <= 2: price_per_pound = 1.50 elif weight <= 6: price_per_pound = 3.00 else: price_per_pound = 4.00 print(f"Shipping cost per pound: ${price_per_pound:.2f}")
内容的提问来源于stack exchange,提问作者Martina
相关产品推荐
相关产品推荐

