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

Python使用eval()遇TypeError:仅能拼接str与str的原因咨询

eval()执行时触发TypeError的原因分析

问题重现

报错信息

print(eval(sol))
File "<string>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

报错代码

userInput1 = str(input("Enter equation. (use ** for exponents): "))
userInput2 = input("Enter value of A: ")
x = userInput2
sol = eval(str("userInput1"))
print(eval(sol))

正常运行的代码

userInput1 = str(input("Enter equation. (use ** for exponents): "))
x = 2
sol = eval(str("userInput1"))
print(eval(sol))

原因解析

  • 变量类型不匹配是核心问题:第一段代码中,x被赋值为userInput2,而input()函数的返回值始终是字符串类型。哪怕用户输入的是数字(比如2),x实际存储的是字符串"2",不是整数2。
  • 当执行eval(sol)时,假设用户输入的表达式是x+2,就等价于执行"2" + 2——Python不允许字符串和整数直接拼接,因此抛出TypeError。
  • 第二段代码中x被直接赋值为整数2,执行x+2时是两个整数相加,符合类型规则,所以能正常运行。

冗余代码优化

代码中的sol = eval(str("userInput1"))属于冗余操作:str("userInput1")生成字符串"userInput1",eval这个字符串的结果就是变量userInput1的值,直接写成sol = userInput1即可,效果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 18:30:09