Python input error: NameError: name 'test' is not defined

Question:

I am a noob at python and just started to learn this. I am trying to follow the book automate the boring stuff with python practical programming for total beginners but receiving error on my first excersise. The book is using python 3 and I am using python 2.7.6

I have tried to change it by putting brackets or taking brackets off but unable to figure it out. Please help in regards to this.

Error:

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

Code Written:

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."
Asked By: crame

||

Answers:

In python 2 you should use raw_input() for getting a string from input.the input function is equivalent to eval(raw_input(prompt)) which evaluate your input.

And in this case when you print 'test' it would be variable test which you didn’t specify any value for it (didn’t initialize it) and so it raises a NameError.

For example :

>>> print myval
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'myval' is not defined

But if I initialize it, the print function will print its value :

>>> myval=3
>>> print myval
3
Answered By: Mazdak

I am guessing you are using Python 2.x (as you are using print statements).

In Python 2.x , input() function tries to evaluate the inputted value before returning, so when you input test , it tries to find the variable/name test causing the issue.

Use raw_input() instead of input() .

Answered By: Anand S Kumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.