Python输入错误:NameError:未定义名称'test'

时间:2015-07-14 14:04:25

标签: python python-2.7

我是python的菜鸟,刚开始学习这个。我试图按照这本书自动化无聊的东西与python实用编程为初学者总,但在我的第一次excersise接收错误。这本书使用的是python 3,我正在使用python 2.7.6

我试图通过放置括号或取消括号来改变它但无法弄明白。请帮忙解决这个问题。

错误:

Traceback (most recent call last):
  File "first.py", line 5, in <module>
    myName = input()
  File "<string>", line 1, in <module>
NameError: name 'test' is not defined

代码编写:

print "Hello world"
print "What is your name?" #ask for their name
myName = input()
print "nice to meet you, " + myName
print "the length of your name is:"
print (len(myName))
print "What is your age?" # asking for age this time
myAge = input()
print "You will be " + str(int(myage) +3) + "in three years."

2 个答案:

答案 0 :(得分:4)

我猜您正在使用public static IResponseObject Post<T, TOut>(string url, T BindingModel) { IResponseObject result; using (var client = new HttpClient()) { var response = client.PostAsJsonAsync(String.Format("{0}{1}", _base, url), BindingModel).Result; if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) result = response.Content.ReadAsAsync<SuccessResponseObject<TOut>>().Result; else result = response.Content.ReadAsAsync<BadRequestResponse>().Result; ((ResponseObject)result).Status = response.StatusCode; return result; } } (因为您正在使用Python 2.x语句)。

在Python 2.x中,print函数尝试在返回之前评估输入的值,因此当您输入input()时,它会尝试查找导致问题的变量/名称test

使用test代替raw_input()

答案 1 :(得分:3)

在python 2中,您应该使用raw_input()从输入中获取字符串。input函数相当于评估输入的eval(raw_input(prompt))

在这种情况下,当您打印'test'时,它将是变量test,您没有为其指定任何值(未初始化它),因此它会引发{{1} }。

例如:

NameError

但如果我初始化它,>>> print myval Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'myval' is not defined 函数将打印其值:

print
相关问题