Simple python code is not working

Viewed 374

The following code is not working:

person = input('Enter your name: ') 
print('Hello', person)

Instead of printing Hello <name> it is giving me the following traceback:

Traceback (most recent call last):
  File  "C:/Users/123/Desktop/123.py", line 1, in <module> 
    person = input('Enter your name: ') 
  File "<string>", line 1, in <module>
NameError: name 'd' is not defined
2 Answers

To read strings you should use:

person = raw_input("Enter your name: ")
print('Hello', person)

When you use input it reads numbers or refers to variables instead. This happens when you are using Python 2.7 or below. With Python 3 and above you have only input function.

Your error states that you entered "d" which is a variable not declared in your code.

So if you had this code instead:

d = "Test"
person = input("Enter your name: ")
print('Hello', person)

And you type now "d" as name, you would get as output:

>>> 
('Hello', 'Test')

What is the error?

You used this:

person = input('Enter your name: ') 

You should have used this:

person = raw_input('Enter your name: ') 

Why these are different

input tries to evaluate what is passed to it and returns the value, whereas raw_input just reads a string, meaning if you want to just read a string you need to use raw_input

In Python 3 input is gone, and raw_input is now called input, although if you really want the old behaviour exec(input()) has the old behaviour.

Related