简体   繁体   中英

Using a dictionary with a while-loop

Im trying to use a dictionary key in the while-loops condition statement, the program won't recognize any input as 'correct'

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!"

Don't ask for the guess before the loop, because if the answer is correct - it won't enter the loop at all. Replace:

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

with:

guess = None

Try this:

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

Here, you're saying "while the passcodes not the gymnast code, check if it's the business code", because by the time you get here, it'll never go inside the while-loop and never finish

   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!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM