AerialAtom AerialAtom - 3 months ago 16
Python Question

Adding a check list and remove from list in Python

So the instruction for the assignment is this


Print a simple set of instructions which will offer users a choice of
keys to open a door.


So the goals that I think will accomplish this is.


make an inventory [rainbow keys]

print the inventory ( you have these keys)

ask to guess key that will open the door

it will check the inventory and if it's a red key it will print "open"

else will print keep guessing and remove the key from the inventory


This is what I have so far. I haven't been able to figure out how to add and check the inventory.

keepGuess = True
correctKey = "red"

while keepGuess:
guess = raw_input("Guess the key to open the door: ")

if guess == correctKey:
print ("You may enter")
keepGuess = False
else:

print ("Keep guessing")

Answer

You're super close. You can just initialize an empty list to store the inventory. When someone guesses a key you just append it to the list. Of course we will check to see if the guessed key is already in the inventory, and if it is, we won't add it.

keepGuess = True
correctKey = "red" 
inventory = []

while keepGuess:
    guess = raw_input("Guess the key to open the door: ")

    if guess == correctKey:
            print ("You may enter")
            inventory.append(guess)
            keepGuess = False
    else:
        if guess not in inventory:
            inventory.append(guess)
        else:
            print ("You have already added this key to your inventory.")
        print ("Keep guessing")

Here's a test:

Guess the key to open the door: blue
Keep guessing
Guess the key to open the door: blue
You have already added this key to your inventory.
Keep guessing
Guess the key to open the door: red
You may enter
Comments