当我运行下面的代码时,我收到以下错误:eval()arg 1必须是字符串或代码对象
任何人都知道为什么?这是我从一本书中学习的代码,所以我认为它是正确的。
# 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)
答案 0 :(得分:5)
您在Python 2上使用input()
,已经在输入上运行eval()
。只需移除eval()
来电,或将input()
替换为raw_input()
。
或者,使用Python 3来运行此代码,它明确针对该版本。如果您的书使用此语法,那么您希望使用正确的版本来运行代码示例。
最重要的是,不要在Python 2上使用input()
或在Python 3上使用eval()
。如果需要整数,请改用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)