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

Python中如何将输入转换为数值类型而非字符串?

解决Python输入字符串转数值类型的问题

Python的input()函数默认将用户输入识别为字符串类型,直接对字符串执行乘法运算会触发错误(比如尝试把两个字符串相乘,Python会认为你想重复字符串,而非数值计算)。要解决这个问题,只需将输入转换为数值类型(float或int)即可。

修改后的代码

# 移除未使用的random模块
time = float(input("What is the time it took? (no label :: "))
speed = float(input("What was the speed?(no label :: "))
distance = speed * time

print(f"Time: {time}")
print(f"Speed: {speed}")
print(f"Distance: {distance}")

关键说明

  • 使用float()转换:考虑到时间和速度可能包含小数(如1.5小时、75.3km/h),float()能兼容整数和小数输入;如果确定输入是整数,也可以用int()替代。
  • 移除了无用的import random:你的代码中并未用到这个模块,删除后更简洁。
  • 优化打印输出:用f-string格式化输出,让结果可读性更强。

可选:处理非法输入

如果需要防止用户输入非数字内容导致程序崩溃,可以添加异常捕获:

try:
    time = float(input("What is the time it took? (no label :: "))
    speed = float(input("What was the speed?(no label :: "))
    distance = speed * time
    print(f"Time: {time}")
    print(f"Speed: {speed}")
    print(f"Distance: {distance}")
except ValueError:
    print("请输入有效的数字!")

内容的提问来源于stack exchange,提问作者Nico.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:45:32