2013-06-20 84 views
0

當我運行下面的代碼時,出現以下錯誤: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) 

回答

5

您正在使用input()在Python 2中,其中已經運行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) 
相關問題