2017-05-31 206 views
0

這是我在這個網站上的第一篇文章,請告訴我,如果我張貼在錯誤的地方或東西。Python初學者試圖瞭解如何運行input()函數

所以......我使用的是幾個星期前開始學習的Python 3.x的Mac版本,並且在這裏面臨一些麻煩的理解。

在文本編輯器,我寫並保存:

>a = input("> ") <br> 
print("A boy goes to" + a) 

然後:

> > 

而且還給我:

> > school 
Traceback (most recent call last): 
    File "workspace/main.py", line 3, in <module> 
    a = input("> ") 
    File "<string>", line 1, in <module> 
NameError: name 'school' is not defined 

我做了什麼錯?

+0

如果你看到'>>>'仍然是Python的命令提示符,並且輸入'school'導致那個錯誤,那麼你沒有運行該程序。您保存程序退出命令解釋程序,然後運行保存的程序 – Anthon

+1

該錯誤與使用Python 2.x運行腳本一致。 –

回答

1

這是一個有點不清楚你做了什麼,而那些「>>」是有點奇怪我,平時蟒蛇有3個「>」當你執行它。

python中的輸入函數會停止執行,並等待用戶輸入某些內容(或不輸入內容)並按下回車鍵(enter)。您可以將從鍵盤輸入的用戶分配給變量,就像您一樣。

variable = input("Some text to show the user what he should do") 
# Execution will stop until user presses enter 
print(variable) # Will print whatever the user typed when the above text was printed to him. 

有一點需要注意的是:如果你在交互模式下執行蟒蛇,它會要求你輸入你輸入你問用戶的輸入值之後。

1

如果您正在使用python 2.7編寫school用雙引號將其作爲字符串。

E.g.在Python 2.7空閒的例子:

>>> a = input("> ") 
> "school" 
>>> print("A boy goes to " + a) 
A boy goes to school