TypeError:只能在我使用 eval() 时连接 str

问题描述 投票:0回答:2

所以我遇到了这个错误:

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
python eval
2个回答
0
投票

userInput2
在您的代码中未转换为 int,因此 python 解释器认为它是字符串(
input
函数的输出),您应该通过以下方式转换它:

userInput2 = int(input("Enter value of A: "))

0
投票

正如 Jaroszewski Piotr 所强调的,问题在于

input
返回字符串,因此您需要将其转换为
int
。但我也认为您的代码包含不必要的步骤。有关信息,请参阅此处的提案。

equation = input("Enter equation. (use ** for exponents): ")
x = int(input("Enter value of A: "))
print(f"{equation} = {eval(equation)}")

# Enter equation. (use ** for exponents): x + 2
# Enter value of A: 3
# x + 2 = 5
© www.soinside.com 2019 - 2024. All rights reserved.