[python] Python Traceback (most recent call last)

I am getting an error executing this code:

nameUser=input("What is your name ? ")    
print (nameUser)

The error message is

Traceback (most recent call last): File "C:/Users/DALY/Desktop/premier.py", line 1, in File "", line 1, in NameError: name 'klj' is not defined

What's going on?

This question is related to python python-2.7

The answer is


In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

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

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'