使用带有while循环的字典

时间:2013-09-20 20:55:09

标签: python dictionary while-loop

我试图在while-loops条件语句中使用字典键,程序将不会将任何输入识别为“正确”

class Gymnast_room(KeyCode):    
    def enter(self):
        print "This is the gymnastics room, we got foam pits and rings!"
        print "Before you can enter, you have to enter the code"
        guess = int(raw_input('What is the code? >>'))

        passcodes = {'Gymnast_code': 1234,
        'Powerlifting_code': 1234
        }
        while guess != passcodes['Gymnast_code']:
            guess = int(raw_input('What is the code? >>'))
            if guess == passcodes['Gymnast_code']:
                print "Correct!"
                return Powerlifting_room()
            else:
                print "Incorrect!"

3 个答案:

答案 0 :(得分:5)

不要在循环之前询问guess,因为如果答案是正确的 - 它根本不会进入循环。替换:

guess = int(raw_input('What is the code? >>'))

使用:

guess = None

答案 1 :(得分:2)

试试这个:

def enter(self):
    print "This is the gymnastics room, we got foam pits and rings!"
    print "Before you can enter, you have to enter the code"
    guess = int(raw_input('What is the code? >>'))

    passcodes = {'Gymnast_code': 1234,
    'Powerlifting_code': 1234
    }
    while guess != passcodes['Gymnast_code']:
        print "Incorrect!"
        guess = int(raw_input('What is the code? >>'))

    print "Correct!"
    return Powerlifting_room()

答案 2 :(得分:1)

在这里,你说“虽然密码不是体操运动员代码,但检查它是否是商业代码”,因为当你到达这里时,它永远不会进入while循环而永远不会完成

   while guess != passcodes['Gymnast_code']:
        guess = int(raw_input('What is the code? >>'))
        if guess == passcodes['Gymnast_code']:
            print "Correct!"
            return Powerlifting_room()
        else:
            print "Incorrect!"