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

64jmpszr  于 2023-04-10  发布在  Python
关注(0)|答案(2)|浏览(115)

所以我遇到了这个错误:

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))

它将打印预期的答案,例如,如果userInput1x+2
为什么我在代码的第一个版本中遇到了TypeError?提前感谢
你好,我遇到了这个错误:

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

wixjitnu1#

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

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

8qgya5xd2#

正如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

相关问题