Python 19 · Organise the control desk

Python lesson 19 of 50 · Early intermediate · About 45 minutes

Clean up the mission controller so the command list is easy to read and extend.

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

Mission Use a dictionary of functions and one consistent calling pattern.

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.

Find a handler. Look up the command in ACTIONS.. → Call it consistently. Pass a state and an argument.. → Retest the mission. Keep the route and endings working..
Find a handler → Call it consistently → Retest the mission

Understand the Python in this lesson

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

Make the printed map from pairs

WORLD.items() gives pairs of rooms and their records. for room, info in WORLD.items() unpacks each pair into two names on each turn of the loop. The exits dictionary also has pairs, one direction and its matching destination.

Build a readable sentence from the exits

In ", ".join(f"{way} to {target}" for way, target in info["exits"].items()), the inner generator makes door phrases one at a time. The f-string inserts the direction and destination. join() connects the phrases with a comma and a space.

Keep functions in a dictionary

ACTIONS maps command strings to functions. The value move has no parentheses because the dictionary stores the function itself. The game uses ACTIONS.get(command) to look it up, then action(state, argument) calls the chosen function when a match exists.

Give all commands the same doorway

Every action called by the dispatch table accepts two inputs. Wrappers such as command_look(state, argument) accept the argument and then call the older look(state) with the one input it needs. With a shared shape for calls, one loop can run any listed action.

Refactor the top-level loop

play(state) gives the loop a name. while not state["rescued"] checks the flag before each prompt. Its final return state makes the completed record available to whoever called it. Refactoring means changing how the code is organised while keeping the game’s behaviour consistent.

How the pieces fit Movement, cargo and repair now each have a job. The dispatch loop looks up and runs one job per command. The final checkpoint will also put the starting values inside a function.

Follow one run, step by step
  1. Enter map
    Habitat: north to Workshop, east to Greenhouse appears before the other rooms. Why The lookup picks show_map, which walks through the room and door pairs.
  2. Enter go north
    Pip arrives at the Workshop Why The lookup returns move and north is passed as its second input.
  3. Enter not-a-command
    Unknown command. Try help. Why The dictionary has no matching key, so no action is called.

Predict before you run What would change if you stored move(state, "north") under "go" in ACTIONS?

Reveal the explanation

The parentheses would run move() while the dictionary is being built. That function returns None, so the table would store None instead of a function ready to handle the player’s actual direction.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills Refactoring, Functions as values, Dispatch dictionary.

1. Give each command a handler

The old loop checked command names with a long chain of conditions. Group the actions in a dictionary so each key points to a handler function. The value is a function name on its own, such as move rather than a call. This lets the controller find the right function first and call it after reading the player’s input.

ACTIONS = {
    "look": command_look,
    "status": command_status,
    "go": move,
    "take": take,
    "panel": open_panel,
    "repair": command_repair,
    "map": show_map,
    "help": show_help,
}

2. Keep the same two inputs

Most action functions already accept the state and an argument. Add small wrappers for the helper functions that only need the state. Both command_look and command_repair take two values so the main loop can use one calling pattern. They pass the state on to the original functions, and the unused argument can remain empty.

def command_look(state, argument):
    look(state)


def command_status(state, argument):
    show_status(state)


def command_repair(state, argument):

3. Compare play before and after

Use ACTIONS.get(command) to look up the handler. For a recognised command, call it with state and argument. For an unknown one, give a hint and keep listening. Run the same repair route from the last lesson after changing the controller. If the result differs, compare which handler ran for each command.

action = ACTIONS.get(command)
        if action is None:
            print("Unknown command. Try help.")
        else:
            action(state, argument)

        if not state["rescued"] and power_failed(state):
            print("Battery empty. Mission stopped.")
Complete Python checkpoint · moonbase_19.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"}

CLUES = {"Workshop": "A note reads: Beacon panel code 42."}
PANEL_CODE = "42"

state = {
    "room": "Habitat",
    "energy": 8,
    "parts": [],
    "panel_open": False,
    "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)
    if room in CLUES:
        print(CLUES[room])

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)

def open_panel(state, code):
    if state["room"] != "Beacon":
        print("The panel is at the Beacon.")
    elif code != PANEL_CODE:
        print("Wrong code. Check the Workshop clue.")
    else:
        state["panel_open"] = True
        print("Beacon panel open.")

def repair(state):
    if state["room"] != "Beacon":
        print("Find the Beacon first.")
    elif not all(part in state["parts"] for part in ROOM_PARTS.values()):
        print("You still need the Coil and Cell.")
    elif not state["panel_open"]:
        print("Open the panel before fitting the parts.")
    else:
        state["rescued"] = True
        print("Signal restored. Rescue is on its way!")


def power_failed(state):
    can_finish = (
        state["room"] == "Beacon"
        and all(part in state["parts"] for part in ROOM_PARTS.values())
    )
    return state["energy"] == 0 and not can_finish

def show_map(state, argument):
    for room, info in WORLD.items():
        doors = ", ".join(f"{way} to {target}" for way, target in info["exits"].items())
        print(f"{room}: {doors}")


def show_help(state, argument):
    print("Try: look, status, map, go north, take coil, panel 42, repair, quit.")


def command_look(state, argument):
    look(state)


def command_status(state, argument):
    show_status(state)


def command_repair(state, argument):
    repair(state)


ACTIONS = {
    "look": command_look,
    "status": command_status,
    "go": move,
    "take": take,
    "panel": open_panel,
    "repair": command_repair,
    "map": show_map,
    "help": show_help,
}

def play(state):
    print("Moonbase Rescue")
    look(state)
    show_help(state, "")
    while not state["rescued"]:
        try:
            raw = input("Pip > ")
        except EOFError:
            print("Radio closed.")
            break
        command, argument = read_command(raw)
        if command == "quit":
            print("Mission paused.")
            break

        action = ACTIONS.get(command)
        if action is None:
            print("Unknown command. Try help.")
        else:
            action(state, argument)

        if not state["rescued"] and power_failed(state):
            print("Battery empty. Mission stopped.")
            break
    return state

play(state)

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–28
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.
Line 10 CLUES = {"Workshop": "A note reads: Beacon panel code 42."}
Work out the value on the right, then store it in CLUES. Each colon pairs a key with its value.
Line 11 PANEL_CODE = "42"
Work out the value on the right, then store it in PANEL_CODE.
Lines 13–19 state = { "room": "Habitat", "energy": 8, "parts": [], "panel_open": False, "rescued": False, }
Work out the value on the right, then store it in state. Each colon pairs a key with its value.
Line 21 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 22 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 23 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 24 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 25 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 26 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 27 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 28 print("You can see a", part)
Show the message or value in the output.
Lines 29–44
Line 29 if room in CLUES:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 30 print(CLUES[room])
Show the message or value in the output. The brackets look up a dictionary key or a position that starts at zero.
Line 32 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 33 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.
Line 34 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 36 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 37 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 38 if not words:
Run the indented block only if this check is true. The word not reverses which result counts as true.
Line 39 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 40 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 41 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 42 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 44 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.
Lines 45–58
Line 45 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 46 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 47 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 48 print("That direction has no exit here.")
Show the message or value in the output.
Line 49 return
Leave this function now.
Line 50 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 51 print("Pip has no energy left to move.")
Show the message or value in the output.
Line 52 return
Leave this function now.
Line 53 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Line 54 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 55 print("Pip arrives at the", destination)
Show the message or value in the output.
Line 57 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 58 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.
Lines 59–72
Line 59 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 60 print("That part is not here.")
Show the message or value in the output.
Line 61 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 62 print("You already collected that part.")
Show the message or value in the output.
Line 63 else:
Take this branch if the earlier checks for this decision were false.
Line 64 state["parts"].append(part)
Add the value to the end without replacing the earlier entries.
Line 65 print("Collected:", part)
Show the message or value in the output.
Line 67 def open_panel(state, code):
Define open_panel, a reusable piece of the program. Its input names are state, code. The indented body runs when something calls it.
Line 68 if state["room"] != "Beacon":
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 69 print("The panel is at the Beacon.")
Show the message or value in the output.
Line 70 elif code != PANEL_CODE:
Run the indented block only if this check is true.
Line 71 print("Wrong code. Check the Workshop clue.")
Show the message or value in the output.
Line 72 else:
Take this branch if the earlier checks for this decision were false.
Lines 73–88
Line 73 state["panel_open"] = True
Work out the value on the right, then store it in state["panel_open"].
Line 74 print("Beacon panel open.")
Show the message or value in the output.
Line 76 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 77 if state["room"] != "Beacon":
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 78 print("Find the Beacon first.")
Show the message or value in the output.
Line 79 elif not all(part in state["parts"] for part in ROOM_PARTS.values()):
Run the indented block only if this check is true. The word not reverses which result counts as true. Check that every result is true. The expression supplies matching values one at a time to the operation using it.
Line 80 print("You still need the Coil and Cell.")
Show the message or value in the output.
Line 81 elif not state["panel_open"]:
Run the indented block only if this check is true. The word not reverses which result counts as true. The brackets look up a dictionary key or a position that starts at zero.
Line 82 print("Open the panel before fitting the parts.")
Show the message or value in the output.
Line 83 else:
Take this branch if the earlier checks for this decision were false.
Line 84 state["rescued"] = True
Work out the value on the right, then store it in state["rescued"].
Line 85 print("Signal restored. Rescue is on its way!")
Show the message or value in the output.
Line 88 def power_failed(state):
Define power_failed, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Lines 89–113
Lines 89–92 can_finish = ( state["room"] == "Beacon" and all(part in state["parts"] for part in ROOM_PARTS.values()) )
Work out the value on the right, then store it in can_finish. With and, every check must be true. The brackets look up a dictionary key or a position that starts at zero. Check that every result is true.
Line 93 return state["energy"] == 0 and not can_finish
Leave this function now and hand the result back to the line that called it. With and, every check must be true. The brackets look up a dictionary key or a position that starts at zero. The word not reverses which result counts as true.
Line 95 def show_map(state, argument):
Define show_map, a reusable piece of the program. Its input names are state, argument. The indented body runs when something calls it.
Line 96 for room, info in WORLD.items():
Take one item at a time and give it to room, info, then run the indented block. Make the dictionary's key and value pairs available to loop over.
Line 97 doors = ", ".join(f"{way} to {target}" for way, target in info["exits"].items())
Work out the value on the right, then store it in doors. Put strings together with the text before .join separating them. The expression supplies matching values one at a time to the operation using it. Python fills the braces with values before it uses the text.
Line 98 print(f"{room}: {doors}")
Show the message or value in the output. Python fills the braces with values before it uses the text.
Line 101 def show_help(state, argument):
Define show_help, a reusable piece of the program. Its input names are state, argument. The indented body runs when something calls it.
Line 102 print("Try: look, status, map, go north, take coil, panel 42, repair, quit.")
Show the message or value in the output.
Line 105 def command_look(state, argument):
Define command_look, a reusable piece of the program. Its input names are state, argument. The indented body runs when something calls it.
Line 106 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 109 def command_status(state, argument):
Define command_status, a reusable piece of the program. Its input names are state, argument. The indented body runs when something calls it.
Line 110 show_status(state)
Run show_status with the supplied inputs and come back here when it returns.
Line 113 def command_repair(state, argument):
Define command_repair, a reusable piece of the program. Its input names are state, argument. The indented body runs when something calls it.
Lines 114–138
Line 114 repair(state)
Run repair with the supplied inputs and come back here when it returns.
Lines 117–126 ACTIONS = { "look": command_look, "status": command_status, "go": move, "take": take, "panel": open_panel, "repair": command_repair, "map": show_map, "help": show_help, }
Work out the value on the right, then store it in ACTIONS. Each colon pairs a key with its value.
Line 128 def play(state):
Define play, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 129 print("Moonbase Rescue")
Show the message or value in the output.
Line 130 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 131 show_help(state, "")
Run show_help with the supplied inputs and come back here when it returns.
Line 132 while not state["rescued"]:
Check not state["rescued"] before each pass. Repeat the indented work while it is true.
Line 133 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 134 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 135 except EOFError:
Run this part only when the try block raises EOFError.
Line 136 print("Radio closed.")
Show the message or value in the output.
Line 137 break
Leave the nearest loop immediately and continue after it.
Line 138 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.
Lines 139–154
Line 139 if command == "quit":
Run the indented block only if this check is true.
Line 140 print("Mission paused.")
Show the message or value in the output.
Line 141 break
Leave the nearest loop immediately and continue after it.
Line 143 action = ACTIONS.get(command)
Work out the value on the right, then store it in action. Look up a key. Use the given fallback, or None, if the key is missing.
Line 144 if action 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 145 print("Unknown command. Try help.")
Show the message or value in the output.
Line 146 else:
Take this branch if the earlier checks for this decision were false.
Line 147 action(state, argument)
Run action with the supplied inputs and come back here when it returns.
Line 149 if not state["rescued"] and power_failed(state):
Run the indented block only if this check is true. With and, every check must be true. The word not reverses which result counts as true. The brackets look up a dictionary key or a position that starts at zero.
Line 150 print("Battery empty. Mission stopped.")
Show the message or value in the output.
Line 151 break
Leave the nearest loop immediately and continue after it.
Line 152 return state
Leave this function now and hand the result back to the line that called it.
Line 154 play(state)
Run play with the supplied inputs and come back here when it returns.

Test the mission

  • Enter map and follow one of its printed routes using go commands.
  • Play the successful route from lesson 18 again. Check you still get the same signal message.

If something goes wrong

A handler runs before a command is entered.
Store the function itself in ACTIONS. A name followed by parentheses calls it immediately.

Mission extension

Add cargo as a second command name for command_status and test that both names show the same information.