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

Python使用input求和出现字符串拼接问题求助

问题原因与解决方法

问题根源

Python的input()函数返回的是字符串类型,所以你执行a + b时,实际上是对两个字符串做拼接操作,而非数值加法,这就导致输入1和3得到结果13。

解决方案

将输入的字符串转换为数值类型(整数用int(),浮点数用float()),再进行加法运算。另外建议避免使用sum作为变量名,因为sum是Python内置函数,可能引发冲突。

修正后的代码(整数求和)

a = int(input("a value is:"))
b = int(input("b value is:"))
sum_result = a + b
print("the Sum of {0} and {1} is {2}".format(a, b, sum_result))

运行结果

a value is:1
b value is:3
the Sum of 1 and 3 is 4

支持浮点数的版本

如果需要处理小数输入,改用float()转换:

a = float(input("a value is:"))
b = float(input("b value is:"))
sum_result = a + b
print("the Sum of {0} and {1} is {2}".format(a, b, sum_result))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:25:41