NameError:未定义全局名称“PIN”

时间:2012-11-02 13:39:41

标签: python global nameerror

我收到以下错误消息:

Traceback (most recent call last):
 File "/Volumes/KINGSTON/Programming/Assignment.py", line 17, in <module>
    Assignment()
 File "/Volumes/KINGSTON/Programming/Assignment.py", line 3, in Assignment

我的代码是:

def Assignment():
    prompt = 'What is your PIN?'
    result = PIN
    error = 'Incorrect, please try again'
    retries = 2
    while result == PIN:
        ok = raw_input(Prompt)
        if ok == 1234:
            result = menu
        else:
            print error
            retries = retries - 1

        if retries < 0:
            print 'You have used your maximum number of attempts. Goodbye.'

Assignment():
如果有人知道我哪里出错并且可以解释

,那么我会非常感激

1 个答案:

答案 0 :(得分:0)

引发了特定错误,因为当您说result = PIN时,PIN实际上并不存在。因为它不是引号,所以Python假定它是一个变量名,但是当它去检查那个变量是什么时,它找不到任何东西并引发NameError。当您解决此问题时,prompt也会发生这种情况,因为您稍后将其称为Prompt

我不确定这是否是您的完整代码,所以我不确定其他问题是什么,但看起来您正在使用resultPIN来控制你的while循环。请记住,while循环运行,直到它检查的条件是False(或者如果你手动突破它),所以你可以从这样的东西开始,而不是声明额外的变量: / p>

def Assignment():
    # No need to declare the other variables as they are only used once
    tries = 2

    # Go until tries == 0
    while tries > 0:
        ok = raw_input('What is your PIN?')
        # Remember that the output of `raw_input` is a string, so either make your
        # comparison value a string or your raw_input an int (here, 1234 is a string)
        if ok == '1234':
            # Here is another spot where you may hit an error if menu doesn't exist
            result = menu
            # Assuming that you can exit now, you use break
            break
        else:
            print 'Incorrect, please try again'
            # Little shortcut - you can rewrite tries = tries - 1 like this
            tries -= 1

        # I'll leave this for you to sort out, but do you want to show them both
        # the 'Please try again' and the 'Maximum attempts' messages?
        if tries == 0:
            print 'You have used your maximum number of attempts. Goodbye.'