Search code examples
pythonpython-2.7user-input

Python get input from user - error "name not defined"


I am fairly new to python. I am trying to get an input from the user running the script. Below is my script:

print("This is the program to test if we can get the user's input")
users_input = input("Please enter your name. Please note that it should be a single word >>> ")
print("Is this your name? ", users_input)

Going through a few websites, this seems to be enough. But when i run this script and am asked to enter the name, I type the name and as soon as I press enter, I get the below error:

Traceback (most recent call last):
 File "test_input.py", line 3, in <module>
users_input = input("Please enter your name. Please note that it should be a single word >>> ")
  File "<string>", line 1, in <module>
NameError: name 'John' is not defined

I was expecting it to print the name but rather I get this error. Not sure why.


Solution

  • Use raw_input() instead, since you're using Python 2.7.

    raw_input gets the input as text (i.e. the characters that are typed), but it makes no attempt to translate them to anything else; i.e. it always returns a string.

    input gets the input value as text, but then attempts to automatically convert the value into a sensible data type; so if the user types ‘1’ then Python 2 input will return the integer 1, and if the user types ‘2.3’ then Python 2 input will return a floating point number approximately equal to 2.3

    input is generally considered unsafe; it is always far better for the developer to make decisions about how the data is interpreted/converted, rather than have some magic happen which the developer has zero control over.

    It is the reason why that automatic conversion has been dropped in Python 3 - essentially; - raw_input in Python 2 has been renamed to input in Python 3; and there is no equivalent to the Python 2 input magic type conversion functionality.