2012-02-16 147 views
1

我很清楚,這是一個noob問題,但我似乎找不到解決方案,我很新編程但渴望學習。我正在瀏覽python中的第一個google clases,這是我得到的錯誤。名稱未定義錯誤

def both_ends(s): 
    print s[0:2], s[3:5] 
    return 

x = input('...: ') 
both_ends(x) 

[email protected]:~/Desktop/p2$ python test2.py 
...: haloj 
Traceback (most recent call last): 
    File "test2.py", line 10, in <module> 
    x = input('...: ') 
    File "<string>", line 1, in <module> 
NameError: name 'haloj' is not defined 

請解釋一下問題所在。

謝謝

回答

5

在Python 2中,input()需要一個應該立即執行的字符串。如果您想將給定的輸入保存爲字符串(您的意圖),請使用raw_input()

+0

謝謝你,這解決了我的問題,並幫助我理解它。 – Sergei 2012-02-16 17:10:05

2

嘗試raw_input而不是input

爲了擴展,您可能正在閱讀一篇假設您使用Python 3.x的教程,並且您可能正在使用Python 2.x.在Python 2.x中,input實際上評估它獲取的文本,這意味着它認爲haloj是一個變量名;因此NameError。在Python 3.x中,input只是將該文本作爲字符串返回。

您的其他選項是輸入'haloj'而不是haloj。 (注意加引號。)

0

爲此,您應該使用raw_input()而不是input()。當你使用input()時,python實際上是在做一個eval(raw_input()) - 所以它試圖調用你輸入的eval。當你輸入'haloj'時,python尋找一個名爲haloj的變量,當然這個變量不存在。