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

如何限制Python的input()函数仅接收整数和浮点数输入?

问题根因

  • 初始代码错误点:
    • 类型判断逻辑无效:type(weight) == float or int 写法不符合Python语法规则,实际执行等价于(type(weight) == float) or (int),而int作为内置对象在布尔判断中永远为真,因此循环条件始终成立
    • 未做类型转换:Python 3中input()函数默认返回字符串类型,直接和数字做大小比较必然触发类型不兼容报错
  • 直接转float的代码缺陷:没有处理输入非数字场景下的转换异常,会直接抛出ValueError终止程序

解决思路

使用try-except异常捕获机制处理不确定输入的类型转换,这是Python中处理这类场景的标准方案,逻辑如下:

  1. 先获取用户输入的原始字符串
  2. 尝试把输入转换为float类型
  3. 转换成功则进入运费计算逻辑
  4. 转换失败则输出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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:00:01