Python 16 · Collect the Coil and Cell

Python lesson 16 of 50 · Early intermediate · About 40 minutes

Pip needs two repair parts. Make room items collectible, keep them in a cargo list and protect the mission from duplicate pickups.

Pip sits at the crossing of moon tracks near the lit Workshop and Greenhouse, with a beacon on a far ridge.

Mission Store unique items in a list and use membership to check whether a pickup should change it.

Get ready

Read this as the next checkpoint in Pip’s mission. You can also start with the complete program below.

Open the browser Python editor (opens in a new tab), replace its example with the complete checkpoint below and choose Run. Use Python 3.10 or newer.

Look up a part. Read the item in the current room.. → Check the cargo. Make sure this pickup is new.. → Collect it. Add the part once and show it in status..
Look up a part → Check the cargo → Collect it

Understand the Python in this lesson

Read the explanations, then follow the worked example before changing the code.

Give each part an original location

ROOM_PARTS is a dictionary mapping Workshop to Coil and Greenhouse to Cell. state["parts"] is Pip’s list of collected items. A room lookup in take() finds the name of that room’s part. The separate list tells the game which names Pip has already collected.

Explain the two ways to reject a request

part is None or item != part.lower() handles an empty room and a differently named item. != means “does not equal”. The typed argument was made lowercase in the parser, so part.lower() gives it a matching form for comparison. When the first test is true, or already has its answer and skips calling lower() on None.

Check what the cargo contains

part in state["parts"] asks whether the list already has an item equal to the name in part. The elif check runs after the request passes the first test. In look(), part is not None and part not in state["parts"] displays the supply only if both tests are true.

Change the list in place

state["parts"].append(part) adds one item to the end of the existing list. Later, join() uses that same list when it shows the cargo. The code stores the original name, such as "Coil", for the status display and the repair checks.

How the pieces fit Cargo is now remembered in the same mission record as the room and battery. The repair can use the list to ask whether Pip has found both parts.

Follow one run, step by step
  1. Enter take coil in Habitat
    That part is not here. Why Habitat has no key in ROOM_PARTS.
  2. Enter go north and take coil
    Collected: Coil Why Workshop has the Coil and the cargo list is still empty.
  3. Enter take coil again
    You already collected that part. Why The membership test now finds the Coil.
  4. Enter status
    Workshop | Energy: 7 | Cargo: Coil Why The door used one unit and there is one copy of the Coil.

Predict before you run Why does typing take COIL also work in the Workshop?

Reveal the explanation

The command parser turns the typed words lowercase and part.lower() gives "coil" for comparison. The original capitalised name goes into the cargo list.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills List append, Membership with in, Data kept separate from progress.

1. Place one part in each supply room

Put the Coil in the Workshop and the Cell in the Greenhouse. ROOM_PARTS describes where the parts begin. Keep that map fixed and track discoveries in the parts list inside state. This gives every fresh game the original supply rooms and an empty cargo hold.

ROOM_PARTS = {"Workshop": "Coil", "Greenhouse": "Cell"}

2. Check a pickup

The take function looks up the part in the current room. Match the typed name against the lowercase part name, so take coil works with a part displayed as Coil. If the room has no part or holds a different one, print a useful response. If the list already includes the part, stop there. Append a name only after both checks have passed.

def take(state, item):
    part = ROOM_PARTS.get(state["room"])
    if part is None or item != part.lower():
        print("That part is not here.")
    elif part in state["parts"]:
        print("You already collected that part.")
    else:
        state["parts"].append(part)
        print("Collected:", part)

3. Keep the room and cargo display in sync

When the player asks to look, display a part only if the cargo list does not already contain it. Print status before and after a successful pickup and look for one change in the cargo text. Then repeat the same pickup and check that the list stays unchanged.

def look(state):
    room = state["room"]
    info = WORLD[room]
    print(info["scene"])
    print("Exits:", ", ".join(info["exits"]))
    part = ROOM_PARTS.get(room)
    if part is not None and part not in state["parts"]:
        print("You can see a", part)
Complete Python checkpoint · moonbase_16.py
WORLD = {
    "Habitat": {"scene": "Pip wakes in the Habitat.", "exits": {"north": "Workshop", "east": "Greenhouse"}},
    "Workshop": {"scene": "Tools click together in the Workshop.", "exits": {"south": "Habitat", "east": "Beacon"}},
    "Greenhouse": {"scene": "Leaves brush the Greenhouse window.", "exits": {"west": "Habitat", "north": "Beacon"}},
    "Beacon": {"scene": "The Beacon stands quiet.", "exits": {"west": "Workshop", "south": "Greenhouse"}},
}

ROOM_PARTS = {"Workshop": "Coil", "Greenhouse": "Cell"}

state = {
    "room": "Habitat",
    "energy": 8,
    "parts": [],
    "rescued": False,
}

def look(state):
    room = state["room"]
    info = WORLD[room]
    print(info["scene"])
    print("Exits:", ", ".join(info["exits"]))
    part = ROOM_PARTS.get(room)
    if part is not None and part not in state["parts"]:
        print("You can see a", part)

def show_status(state):
    cargo = ", ".join(state["parts"]) or "empty"
    print(f'{state["room"]} | Energy: {state["energy"]} | Cargo: {cargo}')

def read_command(text):
    words = text.strip().lower().split(maxsplit=1)
    if not words:
        return "", ""
    command = words[0]
    argument = words[1].strip() if len(words) == 2 else ""
    return command, argument

def move(state, direction):
    exits = WORLD[state["room"]]["exits"]
    destination = exits.get(direction)
    if destination is None:
        print("That direction has no exit here.")
        return
    if state["energy"] == 0:
        print("Pip has no energy left to move.")
        return
    state["energy"] -= 1
    state["room"] = destination
    print("Pip arrives at the", destination)

def take(state, item):
    part = ROOM_PARTS.get(state["room"])
    if part is None or item != part.lower():
        print("That part is not here.")
    elif part in state["parts"]:
        print("You already collected that part.")
    else:
        state["parts"].append(part)
        print("Collected:", part)

print("Moonbase Rescue")
look(state)
while True:
    try:
        raw = input("Pip > ")
    except EOFError:
        print("Radio closed.")
        break

    command, argument = read_command(raw)
    if command == "quit":
        print("Mission paused.")
        break
    elif command == "look":
        look(state)
    elif command == "status":
        show_status(state)
    elif command == "go":
        move(state, argument)
    elif command == "take":
        take(state, argument)
    else:
        print("Unknown command.")

Read the complete checkpoint line by line

Use this guide beside the checkpoint. Blank lines separate ideas. Indented lines belong to the instruction above them. Lines with brackets still open can carry on below.

Lines 1–27
Lines 1–6 WORLD = { "Habitat": {"scene": "Pip wakes in the Habitat.", "exits": {"north": "Workshop", "east": "Greenhouse"}}, "Workshop": {"scene": "Tools click together in the Workshop.", "exits": {"south": "Habitat", "east": "Beacon"}}, "Greenhouse": {"scene": "Leaves brush the Greenhouse window.", "exits": {"west": "Habitat", "north": "Beacon"}}, "Beacon": {"scene": "The Beacon stands quiet.", "exits": {"west": "Workshop", "south": "Greenhouse"}}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 8 ROOM_PARTS = {"Workshop": "Coil", "Greenhouse": "Cell"}
Work out the value on the right, then store it in ROOM_PARTS. Each colon pairs a key with its value.
Lines 10–15 state = { "room": "Habitat", "energy": 8, "parts": [], "rescued": False, }
Work out the value on the right, then store it in state. Each colon pairs a key with its value.
Line 17 def look(state):
Define look, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 18 room = state["room"]
Work out the value on the right, then store it in room. The brackets look up a dictionary key or a position that starts at zero.
Line 19 info = WORLD[room]
Work out the value on the right, then store it in info. The brackets look up a dictionary key or a position that starts at zero.
Line 20 print(info["scene"])
Show the message or value in the output. The brackets look up a dictionary key or a position that starts at zero.
Line 21 print("Exits:", ", ".join(info["exits"]))
Show the message or value in the output. Put strings together with the text before .join separating them. The brackets look up a dictionary key or a position that starts at zero.
Line 22 part = ROOM_PARTS.get(room)
Work out the value on the right, then store it in part. Look up a key. Use the given fallback, or None, if the key is missing.
Line 23 if part is not None and part not in state["parts"]:
Run the indented block only if this check is true. With and, every check must be true. The is comparison checks identity, such as whether a result is exactly None. Membership checks ask whether an item or key is in a collection.
Line 24 print("You can see a", part)
Show the message or value in the output.
Line 26 def show_status(state):
Define show_status, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 27 cargo = ", ".join(state["parts"]) or "empty"
Work out the value on the right, then store it in cargo. With or, the first true result can settle the check. Put strings together with the text before .join separating them. The brackets look up a dictionary key or a position that starts at zero.
Lines 28–42
Line 28 print(f'{state["room"]} | Energy: {state["energy"]} | Cargo: {cargo}')
Show the message or value in the output. Python fills the braces with values before it uses the text. The brackets look up a dictionary key or a position that starts at zero.
Line 30 def read_command(text):
Define read_command, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 31 words = text.strip().lower().split(maxsplit=1)
Work out the value on the right, then store it in words. Return a copy with whitespace removed from the beginning and end. Return a lowercase copy so capital letters do not change a command. Separate the string into a list of pieces.
Line 32 if not words:
Run the indented block only if this check is true. The word not reverses which result counts as true.
Line 33 return "", ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 34 command = words[0]
Work out the value on the right, then store it in command. The brackets look up a dictionary key or a position that starts at zero.
Line 35 argument = words[1].strip() if len(words) == 2 else ""
Work out the value on the right, then store it in argument. Choose the first value if the condition is true, otherwise choose the value after else. Count the characters or items. Return a copy with whitespace removed from the beginning and end.
Line 36 return command, argument
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 38 def move(state, direction):
Define move, a reusable piece of the program. Its input names are state, direction. The indented body runs when something calls it.
Line 39 exits = WORLD[state["room"]]["exits"]
Work out the value on the right, then store it in exits. The brackets look up a dictionary key or a position that starts at zero.
Line 40 destination = exits.get(direction)
Work out the value on the right, then store it in destination. Look up a key. Use the given fallback, or None, if the key is missing.
Line 41 if destination is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 42 print("That direction has no exit here.")
Show the message or value in the output.
Lines 43–56
Line 43 return
Leave this function now.
Line 44 if state["energy"] == 0:
Run the indented block only if this check is true. The brackets look up a dictionary key or a position that starts at zero.
Line 45 print("Pip has no energy left to move.")
Show the message or value in the output.
Line 46 return
Leave this function now.
Line 47 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Line 48 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 49 print("Pip arrives at the", destination)
Show the message or value in the output.
Line 51 def take(state, item):
Define take, a reusable piece of the program. Its input names are state, item. The indented body runs when something calls it.
Line 52 part = ROOM_PARTS.get(state["room"])
Work out the value on the right, then store it in part. Look up a key. Use the given fallback, or None, if the key is missing. The brackets look up a dictionary key or a position that starts at zero.
Line 53 if part is None or item != part.lower():
Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Return a lowercase copy so capital letters do not change a command.
Line 54 print("That part is not here.")
Show the message or value in the output.
Line 55 elif part in state["parts"]:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection. The brackets look up a dictionary key or a position that starts at zero.
Line 56 print("You already collected that part.")
Show the message or value in the output.
Lines 57–71
Line 57 else:
Take this branch if the earlier checks for this decision were false.
Line 58 state["parts"].append(part)
Add the value to the end without replacing the earlier entries.
Line 59 print("Collected:", part)
Show the message or value in the output.
Line 61 print("Moonbase Rescue")
Show the message or value in the output.
Line 62 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 63 while True:
Repeat the indented work until a break, return or error ends this path.
Line 64 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 65 raw = input("Pip > ")
Work out the value on the right, then store it in raw. Show the prompt and wait for the player to type a line. The answer starts as text.
Line 66 except EOFError:
Run this part only when the try block raises EOFError.
Line 67 print("Radio closed.")
Show the message or value in the output.
Line 68 break
Leave the nearest loop immediately and continue after it.
Line 70 command, argument = read_command(raw)
Give each returned value to the matching name, from left to right. Run read_command with the supplied inputs and come back here when it returns.
Line 71 if command == "quit":
Run the indented block only if this check is true.
Lines 72–83
Line 72 print("Mission paused.")
Show the message or value in the output.
Line 73 break
Leave the nearest loop immediately and continue after it.
Line 74 elif command == "look":
Run the indented block only if this check is true.
Line 75 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 76 elif command == "status":
Run the indented block only if this check is true.
Line 77 show_status(state)
Run show_status with the supplied inputs and come back here when it returns.
Line 78 elif command == "go":
Run the indented block only if this check is true.
Line 79 move(state, argument)
Run move with the supplied inputs and come back here when it returns.
Line 80 elif command == "take":
Run the indented block only if this check is true.
Line 81 take(state, argument)
Run take with the supplied inputs and come back here when it returns.
Line 82 else:
Take this branch if the earlier checks for this decision were false.
Line 83 print("Unknown command.")
Show the message or value in the output.

Test the mission

  • Go to the Workshop and collect the Coil. Then collect the Cell in the Greenhouse and check status shows both.
  • Try to take a Cell in the Workshop and check your cargo stays the same.

If something goes wrong

The same part appears twice in cargo.
Keep the membership check before append. Once the part is in state['parts'], show the repeat message.

Mission extension

Add a spare Fuse to the Habitat. Update the supplies dictionary and verify the room and cargo displays agree.