为什么这个nameError会继续?

时间:2015-11-01 00:56:14

标签: python nameerror

我是一名C程序员,今天开始使用python,只是为了测试,我抛出一些非常简单的代码,我得到了这个非常疯狂的名称错误,我在这里看到了几个,但他们看起来不像联系。

person = input('Enter your name: ')

print('Hello', person)

这是我在终端上得到的:

C:\Users\Matt\Desktop\Python>python input.py
Enter your name: Matheus
Traceback (most recent call last):
File "input.py", line 3, in <module>
 person = input('Enter your name: ')
File "<string>", line 1, in <module>
NameError: name 'Matheus' is not defined

有人知道我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

Python 2尝试将对SNAME COUNT SNAME1 2 SNAME2 1 的调用解释为代码。请尝试input,它应该可以正常工作。

答案 1 :(得分:0)

您正在使用Python 2,而在Python 2中,input的使用在输入上运行eval。因此,当您输入您认为是字符串的内容时,Python会尝试对此进行评估。

input的帮助下:

input(...)
    input([prompt]) -> value

    Equivalent to eval(raw_input(prompt)).

输入演示:

>>> a = input()
2
>>> type(a)
<type 'int'>

必须使用通知引号来获取字符串:

>>> a = input()
"bob"
>>> type(a)
<type 'str'>

最好在Python 2中使用raw_input。因为这甚至是Python 3中使用的方法(但Python 3调用方法input)。

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.

raw_input演示:

不必使用通知引号。

>>> a = raw_input()
bob
>>> type(a)
<type 'str'>
相关问题