所以我遇到了这个错误:
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))
它将打印预期的答案,例如,如果userInput1
是x+2
为什么我在代码的第一个版本中遇到了TypeError
?提前感谢
你好,我遇到了这个错误:
print(eval(sol))
File "<string>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
2条答案
按热度按时间wixjitnu1#
userInput2
在你的代码中没有转换为int,所以python解释器认为它是字符串(从input
函数输出),你应该通过以下方式转换它:8qgya5xd2#
正如Jaroszewski Piotr所强调的,问题在于
input
返回字符串,因此需要将其强制转换为int
。但我也认为您的代码包含不必要的步骤。以下是一个建议。