"NameError: [word that I typed in] is not defined" when trying to read from the keyboard

1

I was following a small tutorial. I did everything exactly as indicated in the tutorial and gave me a variable definition error whereas in the tutorial it did not work.

Can someone explain the error?

Code:

print "hello wolrd"
myName = input("what is your name?")
myVar = "hello"
print (myName)
print (myVar)

Output:

C:\Users\Miguel\Desktop>python poop.py
hello wolrd
what is your name?Miguel
Traceback (most recent call last):
  File "poop.py", line 2, in <module>
    myName = input("what is your name?")
  File "<string">, line 1, in <module>
NameError: name 'Miguel' is not defined

The issue is that in the tutorial when I put the name Miguel was supposed to respond with Hello and is not giving, can someone explain me sff?

    
asked by anonymous 02.08.2016 / 01:58

1 answer

1

Solution :

You are using Python 2 and the tutorial should be using Python 3. Use Python 3 or switch input to raw_input .

Explanation :

The input function of Python 2 is not for reading strings, but for reading something from the keyboard and interpreting it as Python codes. It is equivalent to eval(raw_input()) . As Miguel is not defined and looks like the name of a variable, you get an undefined variable error.

In Python 3, the input function now behaves like raw_input , that is, reads from the keyboard and returns the value as a string.

Unless you have good reasons, since it's starting, I recommend learning Python 3 and not Python 2. It's the present and the future of the language.

    
02.08.2016 / 02:22