3

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
jrtapsell
  • 6,719
  • 1
  • 26
  • 49
  • 2
    What version of Python are you using? This looks like a Python 2 error, and if it is you should use `raw_input()` – MooingRawr Sep 28 '17 at 18:37
  • 2
    How are you running this? On the command-line, an IDE, etc? There's no d in the code, so it's odd that you're getting that answer. – bikemule Sep 28 '17 at 18:37
  • 1
    you should add that you input this "d" – PRMoureu Sep 28 '17 at 18:38
  • When getting started with Python, it is important to be clear on whether you are using Python 2.7 or Python 3.x. In 2017, 3.x is recommended for those that are not maintaining a legacy codebase. So if it doesn't matter to you which you use, you could fix the above by changing which Python you use, rather than changing the code. Either way, be aware of this sort of issue going forward. – Eric Wilson Sep 28 '17 at 19:12

2 Answers2

2

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')
Cedric Zoppolo
  • 4,271
  • 6
  • 29
  • 59
2

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.

Eric Wilson
  • 57,719
  • 77
  • 200
  • 270
jrtapsell
  • 6,719
  • 1
  • 26
  • 49