← Deeper Python in the console

A bag that grows

Add to a list with append(), take out with remove(), check with in, and list it with join().

A shopping basket, a playlist, a to-do list: all lists that grow and shrink while the program runs.

The adventurer needs a bag: a list that starts empty, grows when something is taken and shrinks when it is dropped. Lists have their own commands for that, called with a dot, like text.

PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

bag.py
bag = ["lamp", "map"]
bag.append("key")
bag.remove("map")
print(bag)
print("map" in bag)

bag.append("key") adds to the end of the list; bag.remove("map") takes that item out. What does the bag hold at the end?

What is the first line it prints?

RunRun it and compare the result with your prediction.

Run

Run it and try: take lamp, take key, bag, drop map, drop lamp, bag, quit. The loop keeps asking until quit (break leaves it, as in the console bridge).

bag.py
bag = []
while True:
    command = input("> ").strip().lower()
    words = command.split()
    if command == "quit":
        break
    elif command == "bag":
        print("You carry: " + ", ".join(bag))
    elif len(words) == 2 and words[0] == "take":
        bag.append(words[1])
        print("You take the " + words[1] + ".")
    elif len(words) == 2 and words[0] == "drop":
        if words[1] in bag:
            bag.remove(words[1])
            print("You drop the " + words[1] + ".")
        else:
            print("You don't have a " + words[1] + ".")
    else:
        print("Try: take lamp, drop lamp, bag or quit")
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

bag.py
bag = []
while True:
    command = input("> ").strip().lower()
    words = command.split()
    if command == "quit":
        break
    elif command == "bag":
        print("You carry: " + ", ".join(bag))
    elif len(words) == 2 and words[0] == "take":
        bag.append(words[1])
        print("You take the " + words[1] + ".")
    elif len(words) == 2 and words[0] == "drop":
        if words[1] in bag:
            bag.remove(words[1])
            print("You drop the " + words[1] + ".")
        else:
            print("You don't have a " + words[1] + ".")
    else:
        print("Try: take lamp, drop lamp, bag or quit")

Count the bag after each command.

The line before remove().

A drop that crashes.

Start with an empty bag. Fill in how many things are in it after each command.

commandthings in the bag
take lamp1
take key
drop map
drop lamp
take rope

Why does the drop part check if words[1] in bag first?

You type map and it stops with ValueError: list.remove(x): x not in list. Click the line where it stops.

ModifyChange the code on purpose and check the result.

Modify

When the command is bag, also print how many things are in it.

Need a hint?

len(bag) is how many things are in it. Add a line to the bag command that prints it.

The bag holds at most 3 things. Taking a fourth prints Your bag is full.

Need a hint?

Before bag.append(...), check if len(bag) < 3:. Otherwise print that the bag is full.

Try it yourselfYour edits are saved in this browser.

When the command is bag, also say how many things are in it.

    Run your program. This ticks when your code does all of the above.

    The bag holds at most 3 things.

      Run your program. This ticks when your code does all of the above.

      MakeBuild something new using what you have learned. Expect a few tries; that is normal.

      Make a shopping list

      Write a shopping list app. It keeps asking add, remove, show or done. add asks what to add; remove asks what to remove (and says so if it is not on the list); show prints the list in order (items.sort() puts it in order); done prints the final list and stops.

      Try it yourselfYour edits are saved in this browser.

      A shopping list: add, remove (checked with in), show in order, until done.

        Run your program. This ticks when your code does all of the above.

        Info

        Where this leads

        Next lesson adds the map: rooms and exits stored in dictionaries, so the adventurer can walk from room to room.

        A music app's queue lets you add songs, skip one, and see what is next. What is the queue?

        For teachers

        Students keep an inventory in a list that grows with append() and shrinks with remove(), check with in before removing, list it with join(), and build a shopping list app. About 45 minutes.

        Open the teacher guide: answers, solutions, slides and a worksheet.

        Students will be able to

        Before class

        Read the unit primer first. bag.append(x) adds to the end; bag.remove(x) takes the first x out and stops with a ValueError if it is not there, so check with x in bag first. ", ".join(bag) joins a list of texts into one, with a comma and space between. items.sort() puts the list itself in order. Students met break and while True in the console bridge.

        Running the lesson

        1. Predict: draw the bag as boxes; add one on the end, cross one out.
        2. Run: give students the list of commands to type, then let them invent their own.
        3. Investigate: drop map is the interesting row: nothing changes, thanks to the in check.
        4. Bug task: ask what should happen when someone drops something they do not have.
        5. Make: students write the loop themselves. Point them to the bag program as a pattern.

        The hard part (on purpose)

        Checking with in before remove(). Let the ValueError happen first, then ask what the program should say when the thing isn't in the bag.

        When students get stuck

        Stretch and support

        Stretch: Let the shopping list remember how many of each item (milk x2), ready for next lesson's dictionaries.

        Support: Give students the loop and the done command, and ask them to add add, remove and show one at a time.

        Where it leads

        Next lesson stores rooms and exits in dictionaries. The bag comes back in the text adventure.

        What each step is for

        Now you can
        Next lesson3. A map of roomsStore rooms and exits in dictionaries, look things up by name, put a dictionary inside a dictionary, and count words.