Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"NameError: name '' is not defined" after user input in Python [duplicate]

Tags:

python

I'm completely lost as to why this isn't working. Should work precisely, right?

UserName = input("Please enter your name: ")
print ("Hello Mr. " + UserName)
raw_input("<Press Enter to quit.>")

I get this exception:

Traceback (most recent call last):  
  File "Test1.py", line 1, in <module>
    UserName = input("Please enter your name: ")
  File "<string>", line 1, in <module>
NameError: name 'k' is not defined  

It says NameError 'k', because I wrote 'k' as the input during my tests. I've read that the print statement used to be without parenthesis but that has been deprecated right?

like image 689
Sergio Tapia Avatar asked Jan 19 '10 02:01

Sergio Tapia


People also ask

How do I fix NameError is not defined in Python?

The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.

How do you correct a NameError in Python?

Avoiding NameErrors in Python SyntaxError can be corrected by following the programming language guidelines in a way the interpreter could understand. The NameError can be avoided by using a technique called Exception Handling. Even if we write code without any SyntaxError, the program can result in runtime errors.

What is NameError in Python?

NameErrors are raised when your code refers to a name that does not exist in the current scope. For example, an unqualified variable name. The given code is rewritten as follows to catch the exception and find its type.


2 Answers

Do not use input() in 2.x. Use raw_input() instead. Always.

like image 74
Ignacio Vazquez-Abrams Avatar answered Oct 08 '22 14:10

Ignacio Vazquez-Abrams


In Python 2.x, input() "evaluates" what is typed in. (see help(input)). Therefore, when you key in k, input() tries to find what k is. Because it is not defined, it raises the NameError exception.

Use raw_input() in Python 2.x. In 3.0x, input() is fixed.

If you really want to use input() (and this is really not advisable), then quote your k variable as follows:

>>> UserName = input("Please enter your name: ")
Please enter your name: "k"
>>> print UserName
k
like image 38
ghostdog74 Avatar answered Oct 08 '22 15:10

ghostdog74