2017-09-28 64 views
3

下面的代碼是不工作:簡單的Python代碼是不能工作

person = input('Enter your name: ') 
print('Hello', person) 

而不是打印Hello <name>它給我下面的追溯的:

Traceback (most recent call last): 
    File "C:/Users/123/Desktop/123.py", line 1, in <module> 
    person = input('Enter your name: ') 
    File "<string>", line 1, in <module> 
NameError: name 'd' is not defined 
+2

您使用的是什麼版本的Python?這看起來像一個Python 2錯誤,如果是這樣,你應該使用'raw_input()' – MooingRawr

+2

你是如何運行這個?在命令行上,一個IDE等?代碼中沒有d,所以你得到這個答案很奇怪。 – bikemule

+1

你應該添加,你輸入這個「d」 – PRMoureu

回答

2

要閱讀的字符串,你應該使用:

person = raw_input("Enter your name: ") 
print('Hello', person) 

當您使用input它讀取數字或引用變量代替。當您使用Python 2.7或更低版本時會發生這種情況。與Python 3及以上,你只有input功能。

您的錯誤指出您輸入了「d」,它是未在您的代碼中聲明的變量。

所以,如果你有這樣的代碼來代替:

d = "Test" 
person = input("Enter your name: ") 
print('Hello', person) 

,現在您的姓名輸入 「d」,你會得到作爲輸出:

>>> 
('Hello', 'Test') 
2

有什麼錯誤?

您使用此:

person = input('Enter your name: ') 

你應該使用這樣的:

person = raw_input('Enter your name: ') 

爲什麼它們是不同的

input試圖評估哪些傳遞給它並返回值,而raw_input只是讀取一個字符串,這意味着如果您只想讀取需要使用的字符串raw_input

在Python 3 input已經一去不復返了,raw_input現在叫input,但如果你真的舊行爲exec(input())有老人的行爲。