Python lesson 18 of 50 · Early intermediate · About 45 minutes
Make the final repair meaningful. If Pip brings both parts to the open Beacon panel, a rescue signal goes out.

Mission Code and test clear success and battery-failure conditions.
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.

Understand the Python in this lesson
Read the explanations, then follow the worked example before changing the code.
Check each requirement in order
repair(state) tests location first, cargo second and the panel third. The order decides which hint the player sees. elif not state["panel_open"] asks whether the open flag is false. When every requirement passes, else sets rescued to True.
Ask if every required part is present
ROOM_PARTS.values() supplies the part names Coil and Cell. part in state["parts"] for part in ROOM_PARTS.values() describes how to make one true-or-false membership check for each name. Python calls this a generator expression. all() reads those checks and gives True when each one succeeds. One missing part is enough for it to stop with False.
Name what it means to be able to finish
power_failed() gives the Boolean name can_finish to the combined Beacon and cargo check. The wrapping parentheses let one expression continue across lines. Battery failure means the energy is zero and can_finish is false. At the Beacon with both parts, Pip can still open the panel and repair without using a move.
Ask whether the mission should end
After each command, the loop first checks the rescue flag. Then it calls power_failed(state), whose return gives a Boolean answer. The appropriate break ends the loop before the next prompt.
How the pieces fit You now have a complete game loop with a mission, choices, feedback and endings. The next lesson reorganises how commands are sent to their functions without changing the rescue rules.
-
Collect Coil in Workshop and Cell in Greenhouse
The cargo list contains both names. Why Each successfultakeadds its item to the same list. -
Reach Beacon via four moves and enter
panel 42
The energy is 4 and the panel opens. Why The route spends four of eight units. The panel command spends none. -
Enter
repairSignal restored. Rescue is on its way!Why All three repair requirements pass and the rescued flag ends the loop. -
On a fresh run, shuttle Habitat and Workshop for eight moves
Battery empty. Mission stopped.Why The last move leaves Pip outside Beacon with energy zero, so the power check stops the loop.
Predict before you run Pip reaches the Beacon with the Coil only and enters repair. Which hint appears?
Reveal the explanation
You still need the Coil and Cell. The location passes, then all() finds that Cell is missing. Python skips the later panel test on that call.
Build the checkpoint
Python skills Multiple conditions, all across a list, Game loop exit.
1. Make a checklist for the repair
The repair function checks three things in order. Pip must be at the Beacon, carry the two required parts, and have opened the panel. Each failed check gives a different clue to help the player. The built-in all returns true only when every part name in the supplies map is present in the cargo list.
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!")
2. Let the rover finish with its last unit
When the battery hits zero, Pip stays able to do final station work if both parts are in cargo and the room is Beacon. Otherwise the mission reports that the battery is empty and ends. Open the power_failed function and point to the check that allows a fully equipped rover already at the Beacon to finish.
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
3. Check the ending after every turn
After processing a command, look at the rescue flag. If the signal went out, break ends the command loop. If the battery rule says Pip is stranded, print the ending and stop there too. Try the wrong order once, such as reaching the panel without a part, and check that the game tells you what is missing.
if state["rescued"]:
break
if power_failed(state):
print("Battery empty. Mission stopped.")
break
Complete Python checkpoint · moonbase_18.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
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)
elif command == "panel":
open_panel(state, argument)
elif command == "repair":
repair(state)
else:
print("Unknown command.")
if state["rescued"]:
break
if power_failed(state):
print("Battery empty. Mission stopped.")
breakRead 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–106
-
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
print("Moonbase Rescue") - Show the message or value in the output.
-
Line 96
look(state) - Run look with the supplied inputs and come back here when it returns.
-
Line 97
while True: - Repeat the indented work until a break, return or error ends this path.
-
Line 98
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 99
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 100
except EOFError: - Run this part only when the try block raises EOFError.
-
Line 101
print("Radio closed.") - Show the message or value in the output.
-
Line 102
break - Leave the nearest loop immediately and continue after it.
-
Line 104
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 105
if command == "quit": - Run the indented block only if this check is true.
-
Line 106
print("Mission paused.") - Show the message or value in the output.
Lines 107–119
-
Line 107
break - Leave the nearest loop immediately and continue after it.
-
Line 108
elif command == "look": - Run the indented block only if this check is true.
-
Line 109
look(state) - Run look with the supplied inputs and come back here when it returns.
-
Line 110
elif command == "status": - Run the indented block only if this check is true.
-
Line 111
show_status(state) - Run show_status with the supplied inputs and come back here when it returns.
-
Line 112
elif command == "go": - Run the indented block only if this check is true.
-
Line 113
move(state, argument) - Run move with the supplied inputs and come back here when it returns.
-
Line 114
elif command == "take": - Run the indented block only if this check is true.
-
Line 115
take(state, argument) - Run take with the supplied inputs and come back here when it returns.
-
Line 116
elif command == "panel": - Run the indented block only if this check is true.
-
Line 117
open_panel(state, argument) - Run open_panel with the supplied inputs and come back here when it returns.
-
Line 118
elif command == "repair": - Run the indented block only if this check is true.
-
Line 119
repair(state) - Run repair with the supplied inputs and come back here when it returns.
Lines 120–126
-
Line 120
else: - Take this branch if the earlier checks for this decision were false.
-
Line 121
print("Unknown command.") - Show the message or value in the output.
-
Line 122
if state["rescued"]: - 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 123
break - Leave the nearest loop immediately and continue after it.
-
Line 124
if power_failed(state): - Run the indented block only if this check is true. Run power_failed with the supplied inputs and come back here when it returns.
-
Line 125
print("Battery empty. Mission stopped.") - Show the message or value in the output.
-
Line 126
break - Leave the nearest loop immediately and continue after it.
Test the mission
- Spend eight moves on a Habitat–Workshop shuttle. The mission should end automatically.
- Complete the four-move collection route and confirm the signal message appears exactly once.
If something goes wrong
- The game stops too soon when you reach the Beacon at zero energy.
- Make the battery rule inspect both the room and the complete cargo before deciding the rover is stranded.
Mission extension
Temporarily lower the starting battery to 4 and prove that the shortest collection route can still win.