0

当我运行下面的代码时,我收到以下错误: eval() arg 1 must be a string or code object

有谁知道为什么?这是我从一本书中学习的代码,所以我认为它是正确的。

 # Prompt the user to enter three numbers
number1 = eval(input("Enter the first number: "))
number2 = eval(input("Enter the second number: "))
number3 = eval(input("Enter the third number: "))

 # Compute average
average = (number1 + number2 + number3) / 3

print("The average of", number1, number2, number3, "is", average)
4

1 回答 1

5

您正在使用input()Python 2,它已经eval()在输入上运行。只需删除eval()呼叫,或替换input()raw_input().

或者,使用 Python 3 运行此代码,它显然是针对该版本的。如果您的书使用这种语法,那么您希望使用正确的版本来运行代码示例。

最重要的是,不要input()在 Python 2 或eval()Python 3 上使用。如果需要整数,请int()改用。

Python 2 示例:

# Prompt the user to enter three numbers
number1 = int(raw_input("Enter the first number: "))
number2 = int(raw_input("Enter the second number: "))
number3 = int(raw_input("Enter the third number: "))

# Compute average
average = (number1 + number2 + number3) / 3

print "The average of", number1, number2, number3, "is", average

Python 3 版本:

# Prompt the user to enter three numbers
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
number3 = int(input("Enter the third number: "))

# Compute average
average = (number1 + number2 + number3) / 3

print("The average of", number1, number2, number3, "is", average)
于 2013-06-20T09:27:43.680 回答