2010-01-19 40 views
13

我完全失去了爲什麼這不起作用。應該準確地工作,對嗎?「用戶在Python中輸入後NameError:name''未定義'

UserName = input("Please enter your name: ") 
print ("Hello Mr. " + UserName) 
raw_input("<Press Enter to quit.>") 

我得到這個異常:

Traceback (most recent call last): 
    File "Test1.py", line 1, in <module> 
    UserName = input("Please enter your name: ") 
    File "<string>", line 1, in <module> 
NameError: name 'k' is not defined 

它說NameError 'k',因爲我寫'k'因爲在我的測試輸入。我讀過的印刷語句過去沒有括號,但已被棄用的權利?

+1

'輸入'相當於'eval(raw_input(提示))'。你只需要'raw_input()'。 – 2010-01-19 02:42:15

+1

input()與Python 3k一致。 @OP你使用的是什麼版本的Python? – ghostdog74 2010-01-19 02:50:41

+0

@Sergio這與您的問題無關,但您應該使用小寫第一個字母作爲變量名(例如'userName'而不是'UserName')。 – Roman 2010-01-19 03:00:25

回答

13

請勿在2.x中使用input()。改爲使用raw_input()。總是。

+0

什麼時候使用了Input()?在之前的版本中? – 2010-01-19 02:43:34

+0

是的。 Python版本2.x. http://docs.python.org/library/2to3。html#2to3fixer-input – 2010-01-19 02:45:05

+2

'input()'總是被破壞。 3.x「固定」它,但傷害需要很長時間才能痊癒。 – 2010-01-19 02:45:44

11

在Python 2.x中,input()「評估」輸入的內容(請參閱help(input))。因此,當您輸入k時,input()會嘗試查找k是什麼。由於它沒有定義,所以會引發NameError異常。

在Python 2.x中使用raw_input()。在3.0x中,input()已修復。

如果你真的想使用input()(這真是不可取的),然後引用您的k變量,如下所示:

>>> UserName = input("Please enter your name: ") 
Please enter your name: "k" 
>>> print UserName 
k 
0

接受的答案提供正確的解決方案,並@ ghostdog74給出的理由例外。我認爲一步一步地看到爲什麼這會產生一個NameError(而不是其他的東西,如ValueError):

根據Python 2.7文檔,input() evaluates你輸入了什麼,所以本質上你的程序變成這樣:

username = input('...') 
# => translates to 
username = eval(raw_input('...')) 

假設輸入bob,那麼這將成爲:

username = eval('bob') 

由於eval()執行「鮑勃」就好像它是一個Python表達式,你的程序變成這樣:

username = bob 
=> NameError 
print ("Hello Mr. " + username) 

可能使其工作我進入「鮑勃」(帶引號),因爲那時的計劃是有效的:

username = "bob" 
print ("Hello Mr. " + username) 
=> Hello Mr. bob 

您可以通過在每個步驟去嘗試一下你自己Python REPL。請注意,該異常是在第一行中引發的,而不是在print語句中引發的。

相關問題