2013-04-28 22 views
3

那麼我在這裏做錯了什麼?使用input時NameError()

answer = int(input("What is the name of Dr. Bunsen Honeydew's assistant?")) 
if answer == ("Beaker"): 
    print("Correct!") 
else: 
    print("Incorrect! It is Beaker.") 

不過,我只

Traceback (most recent call last): 
    File "C:\Users\your pc\Desktop\JQuery\yay.py", line 2, in <module> 
    answer = int(input("What is the name of Dr. Bunsen Honeydew's assistant?")) 
    File "<string>", line 1, in <module> 
     NameError: name 'Beaker' is not defined 
+0

你正在使用'int'和你期待一個' string'?試試這個'int(「5」)'和這個'int(「hello」)' – 2013-04-28 17:50:37

回答

8

您正在使用input代替raw_input與Python 2,其分析輸入的Python代碼得到。

answer = raw_input("What is the name of Dr. Bunsen Honeydew's assistant?") 
if answer == "Beaker": 
    print("Correct!") 

input()相當於eval(raw_input())

你也正在試圖 「燒杯」 轉換爲整數,這並沒有太大的意義。

 

你可以在你的腦袋像這樣替換輸入,具有raw_input

answer = "Beaker" 
if answer == "Beaker": 
    print("Correct!") 

而且隨着input

answer = Beaker  # raises NameError, there's no variable named Beaker 
if answer == "Beaker": 
    print("Correct!") 
0

你爲什麼要使用int和期待串輸入。使用raw_input您的情況,它捕獲的每個可能的值answer作爲字符串。所以你的情況會是這樣的:

answer = raw_input("What is the name of Dr. Bunsen Honeydew's assistant?") 
#This works fine and converts every input to string. 
if answer == 'Beaker': 
    print ('Correct') 

OR

,如果你只使用input。期待'回答'或'回答'字符串。像:

>>> answer = input("What is the name of Dr. Bunsen Honeydew's assistant?") 
What is the name of Dr. Bunsen Honeydew's assistant?'Beaker'#or"Beaker" 
>>> print answer 
Beaker 
>>> type(answer) 
<type 'str'> 

同樣在input使用int,使用它像:

>>> answer = input("What is the name of Dr. Bunsen Honeydew's assistant?") 
What is the name of Dr. Bunsen Honeydew's assistant?12 
>>> type(answer) 
<type 'int'> 

但是,如果你輸入:

>>> answer = input("What is the name of Dr. Bunsen Honeydew's assistant?") 
What is the name of Dr. Bunsen Honeydew's assistant?"12" 
>>> type(answer) 
<type 'str'> 
>>> a = int(answer) 
>>> type(a) 
<type 'int'>