2017-05-31 156 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