开发者

New to Python: getting NameError in variable [duplicate]

This question already has answers here: error in python d not defined. [duplicate] (3 answers) Closed 8 years ago.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜