12

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

8

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.

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • Why is the function is designed in such a way. The purpose of the function is to just accept the input. What is the need of evaluation of what has been input. – Krishna Oza Dec 16 '16 at 08:49
  • @darth_coder: the purpose of `raw_input()` is to just accept input and return it as a string. `input()` is different; it evaluates the input. That's how these two functions are defined. Since `raw_input()` was renamed to `input()` in Python 3, and `input()` removed altogether, it seems that it was not worth the confusion caused by the poorly named (IMHO) `input()` function. What purpose could it have? If you want to execute user input is one obvious application. – mhawke Dec 16 '16 at 10:03
  • @mhwake fine but I wanted to understand the design semantic behind the `input` function. I am still confused on what exactly it means to evaluate the input. – Krishna Oza Dec 18 '16 at 10:58
  • 1
    @darth_coder: in Python 2 `input()` is equivalent to `eval(raw_input())`, so that's what it means to "evaluate the input". Read what `eval()` does for more details. As I suggested, one reason for the existence of `input()` is so that you can easily evaluate user input. If that is not a satisfactory explanation then I think that your question reduces to "what is the purpose of `eval()`?" because that is ultimately what is going on. – mhawke Dec 19 '16 at 03:19
3

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'
timgeb
  • 76,762
  • 20
  • 123
  • 145