Python 24 · Keep mission state predictable

Python lesson 24 of 50 · Intermediate · About 24 minutes

Review every state field and the action that can change it. Then check that incorrect commands do not take energy or grant bonus parts.

Pip presses a control in front of three mint-green mission screens.

Mission Make a set of before-and-after checks for room, energy, parts and rescue status.

Get ready

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

Save the complete checkpoint below as moonbase_24.py in a project folder and run python moonbase_24.py from that folder. Use python3 on systems where that is the Python 3 command. Use Python 3.10 or newer.

Before. Record the four mission fields.. → Guard. Reject an invalid or repeated action early.. → After. A valid action changes only the relevant fields..
Before → Guard → After

Understand the Python in this lesson

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

Know which values stay between turns

state is a dictionary with these fields: room, energy, parts and rescued. It stays in use each time the loop goes around. The current room and charge change when Pip moves. The list of parts changes when Pip picks something up. The rescued flag changes when the last rule passes.

Put the guard before the update

A guard checks whether an action can happen. In move, a blocked exit pulls the program out with an early return. The charge guard does the same when energy is zero. Only after both guards do state["room"] = destination and state["energy"] -= 1 change the mission.

See what it means to change a list

state["parts"].append(item) adds to the live list inside the dictionary. The membership check item in state["parts"] runs first. A second attempt at the same part reaches an early return, so it cannot add a duplicate. Changing an existing object this way is called mutation.

Capture an independent catalogue of parts

mission_snapshot(state) returns four values together as a tuple. The expression tuple(state["parts"]) builds a tuple from the list’s current items. Tuples keep the same entries after they are created. The entries here are strings, so a stored snapshot of the cargo stays the same when the live list gets a new part later.

Unpack a snapshot for the radio report

In room, energy, cargo, _ = mission_snapshot(state), the names receive values in tuple order. The report uses room, energy and cargo. _ is the conventional name for an ignored result, which is the rescued flag here.

How the pieces fit Each action owns a particular state change, and a snapshot is for reading. This separation makes failed-command checks easier today and becomes useful when you save, load and test the game.

Follow one run, step by step
  1. Imagine storing a snapshot at the first prompt.
    It contains Habitat, energy 8, empty cargo and False. Why new_mission supplies the initial values.
  2. Enter west from Habitat.
    Room and charge stay the same. Why The blocked-exit guard returns before either state update.
  3. Enter east, then take twice.
    Pip is in Workshop with energy 7 and one Coil. Why The legal move updates the charge, and the second pickup is rejected.
  4. Compare the stored snapshot with a fresh look.
    The original cargo is empty; the fresh report lists Coil. Why The original tuple kept the list contents from the moment it was made.

Predict before you run If you replace tuple(state["parts"]) with state["parts"], will the old snapshot’s cargo stay empty after take?

Reveal the explanation

Both the dictionary and the snapshot would point to the same list. append would update that shared list. Keeping the tuple(...) conversion records the earlier cargo separately.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills state, guards, mutability, invariants.

1. Draw a state record before running

The current mission has four fields: Pip’s room, energy remaining, a list of parts and the rescue flag. Write their starting values from new_mission on paper. Move once, collect a part, then update only the fields touched by each action. Program state is the information that remains between prompts.

def new_mission():
    return {"room": "Habitat", "energy": 8, "parts": [], "rescued": False}

2. Look for all the guards

A guard is a test that stops an action early when its requirements are missing. The move guard rejects a blocked exit before subtracting from energy. The collect guards reject a missing or already collected part before appending. Keep these checks above the statements that update the dictionary.

def collect(state):
    item = WORLD[state["room"]]["part"]
    if item is None:
        return "There is no repair part here."
    if item in state["parts"]:
        return f"You already have the {item}."
    state["parts"].append(item)
    return f"Collected the {item}."

3. Investigate an input error

Type go on its own, then ask Pip to look. The parser can reject the incomplete command and preserve your report. Try a blocked direction next. Both mistakes leave the original state intact, but the radio can give different messages. Those separate messages are useful clues when you debug.

def apply(state, verb, argument):
    if verb == "look":
        return describe(state)
    if verb == "go":
        return move(state, argument)
    if verb == "take":
        return collect(state)
    if verb == "repair":

4. Take a snapshot the next action cannot change

The new snapshot returns the room, energy, a tuple of parts and the rescue flag as one record. The tuple captures the current entries independently of the live parts list. Compare your look output before and after a failed command, then after a successful pickup. Only the latter should alter the cargo.

def mission_snapshot(state):
    return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]
Complete Python checkpoint · moonbase_24.py
WORLD = {
    "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None},
    "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"},
    "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"},
    "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None},
}
REQUIRED = {"Coil", "Cell"}


def new_mission():
    return {"room": "Habitat", "energy": 8, "parts": [], "rescued": False}


def can_repair(room, parts):
    return room == "Beacon" and REQUIRED.issubset(parts)


def describe(state):
    room, energy, cargo, _ = mission_snapshot(state)
    exits = ", ".join(WORLD[room]["exits"])
    parts = ", ".join(cargo) or "none"
    return f"{room} | energy {energy} | parts {parts} | exits {exits}"


def collect(state):
    item = WORLD[state["room"]]["part"]
    if item is None:
        return "There is no repair part here."
    if item in state["parts"]:
        return f"You already have the {item}."
    state["parts"].append(item)
    return f"Collected the {item}."


def repair(state):
    if can_repair(state["room"], state["parts"]):
        state["rescued"] = True
        return "Beacon restored! Pip has sent the rescue signal."
    return "Bring the Coil and the Cell to the Beacon."


def move(state, direction):
    destination = WORLD[state["room"]]["exits"].get(direction)
    if destination is None:
        return "That route is blocked."
    if state["energy"] == 0:
        return "Pip is out of energy."
    state["room"] = destination
    state["energy"] -= 1
    return f"Moved to {destination}."


def parse_command(text):
    words = text.lower().split()
    if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
        return "go", words[0]
    if len(words) == 2 and words[0] == "go":
        return "go", words[1]
    if len(words) == 1 and words[0] in {"look", "take", "repair", "quit"}:
        return words[0], ""
    return "", ""


def mission_snapshot(state):
    return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]


def apply(state, verb, argument):
    if verb == "look":
        return describe(state)
    if verb == "go":
        return move(state, argument)
    if verb == "take":
        return collect(state)
    if verb == "repair":
        return repair(state)
    return "Unknown command."


def run():
    state = new_mission()
    print("Moonbase Rescue | Pip on duty")
    print(describe(state))
    print("Try look, go, take, repair or quit.")
    while not state["rescued"]:
        try:
            raw = input("Pip> ")
        except EOFError:
            print("Radio closed.")
            break
        verb, argument = parse_command(raw)
        if verb == "quit":
            print("Pip is on standby.")
            break
        print(apply(state, verb, argument))


if __name__ == "__main__":
    run()

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–26
Lines 1–6 WORLD = { "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None}, "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"}, "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"}, "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 7 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 10 def new_mission():
Define new_mission, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 11 return {"room": "Habitat", "energy": 8, "parts": [], "rescued": False}
Leave this function now and hand the result back to the line that called it. Each colon pairs a key with its value.
Line 14 def can_repair(room, parts):
Define can_repair, a reusable piece of the program. Its input names are room, parts. The indented body runs when something calls it.
Line 15 return room == "Beacon" and REQUIRED.issubset(parts)
Leave this function now and hand the result back to the line that called it. With and, every check must be true. Check whether every item in this set appears in the other collection.
Line 18 def describe(state):
Define describe, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 19 room, energy, cargo, _ = mission_snapshot(state)
Give each returned value to the matching name, from left to right. Run mission_snapshot with the supplied inputs and come back here when it returns.
Line 20 exits = ", ".join(WORLD[room]["exits"])
Work out the value on the right, then store it in exits. 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 21 parts = ", ".join(cargo) or "none"
Work out the value on the right, then store it in parts. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Line 22 return f"{room} | energy {energy} | parts {parts} | exits {exits}"
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 25 def collect(state):
Define collect, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 26 item = WORLD[state["room"]]["part"]
Work out the value on the right, then store it in item. The brackets look up a dictionary key or a position that starts at zero.
Lines 27–43
Line 27 if item 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 28 return "There is no repair part here."
Leave this function now and hand the result back to the line that called it.
Line 29 if item 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 30 return f"You already have the {item}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 31 state["parts"].append(item)
Add the value to the end without replacing the earlier entries.
Line 32 return f"Collected the {item}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 35 def repair(state):
Define repair, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 36 if can_repair(state["room"], state["parts"]):
Run the indented block only if this check is true. Run can_repair with the supplied inputs and come back here when it returns. The brackets look up a dictionary key or a position that starts at zero.
Line 37 state["rescued"] = True
Work out the value on the right, then store it in state["rescued"].
Line 38 return "Beacon restored! Pip has sent the rescue signal."
Leave this function now and hand the result back to the line that called it.
Line 39 return "Bring the Coil and the Cell to the Beacon."
Leave this function now and hand the result back to the line that called it.
Line 42 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 43 destination = WORLD[state["room"]]["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.
Lines 44–58
Line 44 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 45 return "That route is blocked."
Leave this function now and hand the result back to the line that called it.
Line 46 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 47 return "Pip is out of energy."
Leave this function now and hand the result back to the line that called it.
Line 48 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 49 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Line 50 return f"Moved to {destination}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 53 def parse_command(text):
Define parse_command, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 54 words = text.lower().split()
Work out the value on the right, then store it in words. Return a lowercase copy so capital letters do not change a command. Separate the string into a list of pieces.
Line 55 if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Line 56 return "go", words[0]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 57 if len(words) == 2 and words[0] == "go":
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. The brackets look up a dictionary key or a position that starts at zero.
Line 58 return "go", words[1]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Lines 59–75
Line 59 if len(words) == 1 and words[0] in {"look", "take", "repair", "quit"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Line 60 return words[0], ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 61 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 64 def mission_snapshot(state):
Define mission_snapshot, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 65 return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero. Collect ordered items in a tuple, whose entries cannot be reassigned.
Line 68 def apply(state, verb, argument):
Define apply, a reusable piece of the program. Its input names are state, verb, argument. The indented body runs when something calls it.
Line 69 if verb == "look":
Run the indented block only if this check is true.
Line 70 return describe(state)
Leave this function now and hand the result back to the line that called it. Run describe with the supplied inputs and come back here when it returns.
Line 71 if verb == "go":
Run the indented block only if this check is true.
Line 72 return move(state, argument)
Leave this function now and hand the result back to the line that called it. Run move with the supplied inputs and come back here when it returns.
Line 73 if verb == "take":
Run the indented block only if this check is true.
Line 74 return collect(state)
Leave this function now and hand the result back to the line that called it. Run collect with the supplied inputs and come back here when it returns.
Line 75 if verb == "repair":
Run the indented block only if this check is true.
Lines 76–90
Line 76 return repair(state)
Leave this function now and hand the result back to the line that called it. Run repair with the supplied inputs and come back here when it returns.
Line 77 return "Unknown command."
Leave this function now and hand the result back to the line that called it.
Line 80 def run():
Define run, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 81 state = new_mission()
Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
Line 82 print("Moonbase Rescue | Pip on duty")
Show the message or value in the output.
Line 83 print(describe(state))
Show the message or value in the output. Run describe with the supplied inputs and come back here when it returns.
Line 84 print("Try look, go, take, repair or quit.")
Show the message or value in the output.
Line 85 while not state["rescued"]:
Check not state["rescued"] before each pass. Repeat the indented work while it is true.
Line 86 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 87 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 88 except EOFError:
Run this part only when the try block raises EOFError.
Line 89 print("Radio closed.")
Show the message or value in the output.
Line 90 break
Leave the nearest loop immediately and continue after it.
Lines 91–99
Line 91 verb, argument = parse_command(raw)
Give each returned value to the matching name, from left to right. Run parse_command with the supplied inputs and come back here when it returns.
Line 92 if verb == "quit":
Run the indented block only if this check is true.
Line 93 print("Pip is on standby.")
Show the message or value in the output.
Line 94 break
Leave the nearest loop immediately and continue after it.
Line 95 print(apply(state, verb, argument))
Show the message or value in the output. Run apply with the supplied inputs and come back here when it returns.
Line 98 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 99 run()
Run run with the supplied inputs and come back here when it returns.

Test the mission

  • Write down the starting energy, try west, then look.
  • Go east, take twice and look. Check Coil is listed once.
  • Try repair with one part. Verify you can still issue commands.

If something goes wrong

A blocked move drains energy.
Return on the blocked route before subtracting from the energy field.

Mission extension

Add a successful-moves counter. Decide what blocked actions should do before adding code.