Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Traceback (most recent call last) [duplicate]

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 <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

What's going on?

like image 406
Mohamed Ali Benmansour Avatar asked Feb 18 '16 22:02

Mohamed Ali Benmansour


2 Answers

You are using Python 2 for which the input() function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError exception.

To fix the problem, in Python 2, you can use raw_input(). This returns the string entered by the user and does not attempt to evaluate it.

Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

like image 75
mhawke Avatar answered Oct 19 '22 01:10

mhawke


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'
like image 3
timgeb Avatar answered Oct 19 '22 00:10

timgeb