"Nameerror: [word I typed] is not defined" when trying to read from keyboard

Asked

Viewed 2,620 times

1

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

Can someone explain to me the mistake?

Code:

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

Exit:

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 question is that in the tutorial when I put the name Miguel was supposed to answer with Hello and is not giving, someone can explain me sff?

  • Use raw_input instead of input.

  • Hello and welcome. Please do not place images with your code or error output. Instead, paste the content here. This facilitates future searches and allows screen reader users to view content.

1 answer

1


Solution:

You are using Python 2 and the tutorial must be using Python 3. Use Python 3 or swap input for raw_input.

Explanation:

The function input Python 2 is not to read strings, but to read something from the keyboard and interpret it as Python codes. It is equivalent to eval(raw_input()). Like Miguel is not set and looks like a variable name, you get an undefined variable error.

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

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

  • 1

    Ohhh Thank you Thank you!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.