"NameError: name '' is not defined" after user input in Python [duplicate]
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?
Do not use input()
in 2.x. Use raw_input()
instead. Always.
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