0

我收到以下错误消息:

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():

如果有人知道我哪里出错并且可以解释,我将非常感谢您的帮助

4

1 回答 1

0

引发该特定错误是因为当您说result = PIN,PIN实际上并不存在。由于它不在引号中,Python 假定它是一个变量名,但是当它检查该变量等于什么时,它什么也没找到并引发NameError. 当您修复它时,它也会发生,prompt因为您稍后将其称为Prompt.

我不确定这是否是您的完整代码,所以我不确定其他问题可能是什么,但看起来您正在使用resultPIN控制您的while循环。请记住,while循环会一直运行,直到它检查的条件是False(或者如果您手动退出它),因此您可以从以下内容开始,而不是声明额外的变量:

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.'
于 2012-11-02T14:08:47.007 回答