【问题标题】:New to Python: getting NameError in variable [duplicate]Python 新手:在变量中获取 NameError [重复]
【发布时间】:2011-07-22 21:53:29
【问题描述】:

NameError: 名称“Brandon”未定义

我在 Python 2.7.2 中有一个简单的用户名/密码程序,并且不断收到这个愚蠢的错误消息。

这是我的代码:

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"

【问题讨论】:

    标签: python


    【解决方案1】:

    您应该使用 raw_input 而不是 input,因为 input 期望您正在输入 python 代码。更准确地说,您的麻烦在于Username == brandonbrandon 将是一个变量。 'brandon' 将是一个用于比较的字符串。

    【讨论】:

    • 非常感谢!我用 raw_input 得到了同样的结果。不过,我不想把布兰登放在引号中,因为我认为它会变成我不想要的东西,因为我现在只将它用于打印命令。
    • @Brandon - 很高兴为您提供帮助。请务必接受答案,以便您继续从其他用户那里收到高质量的答案。
    【解决方案2】:

    使用raw_input 代替input

    input 本质上是在运行eval(raw_input(...))。而且你不想在这里做eval

    另外,你的password == 42 应该是password == "42",因为raw_input 会返回一个字符串。

    【讨论】:

    • 我使用 raw_input 得到了同样的结果,但我会再次检查。编辑:是的,得到同样的错误。
    【解决方案3】:
    # 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
    

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多