New to Python: getting NameError in variable [duplicate]
NameError: name 'Brandon' is not defined
I have a simple username/password program in Python 2.7.2 and keep getting this dumb error message.
Here's my code:开发者_如何学C
Username = input ("Please enter your username: ")
if Username == brandon:
password = input ("Correct! Please enter password: ")
if password == 42:
print "Access granted!"
else:
print "Wrong Password!"
else:
print "Wrong username"
You should use raw_input instead of input, because input expect that you're entering python code. More accurately though, your trouble is in Username == brandon
. brandon
would be a variable. 'brandon'
would be a string for use in comparison.
Use raw_input
instead of input
.
input
is essentially running eval(raw_input(...))
. And you don't want to do an eval
here.
Also, your password == 42
should probably be password == "42"
, since raw_input
gives back a string.
# raw_input() reads every input as a string
# then it's up to you to process the string
str1 = raw_input("Enter anything:")
print "raw_input =", str1
# input() actually uses raw_input() and then tries to
# convert the input data to a number using eval()
# hence you could enter a math expression
# gives an error if input is not numeric eg. $34.95
x = input("Enter a number:")
print "input =", x
精彩评论