Python lesson 17 of 50 · Early intermediate · About 40 minutes
Give explorers a clue in the Workshop and a code lock that only opens at the Beacon.

Mission Add a state flag and use separate tests for location and code.
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.
Store and find the clue
CLUES has a Workshop key whose value is a sentence containing the code. if room in CLUES checks whether the room name is a dictionary key. Only then does CLUES[room] read the sentence. This also lets look() run in rooms with no clue.
Compare the same sort of value
PANEL_CODE = "42" stores the digits as text. Commands arrive through input() as strings, so the second part of panel 42 is also the string "42". code != PANEL_CODE can compare the typed text directly to the answer.
Give the player the first useful answer
open_panel() checks whether Pip is at the Beacon. If that test is false, the elif checks whether the code is wrong. The else works when Pip is at the Beacon and the code is correct. In this chain, Python runs the first matching branch and continues after the chain.
Remember the solved puzzle
state["panel_open"] begins as False, a closed-panel flag. The success branch changes it to True. The stored value lets a later command ask whether Pip already solved the puzzle. Entering the panel command uses no battery.
How the pieces fit The puzzle adds a condition the rescue can check later. Pip needs the right room, the right parts and an open panel to finish the mission.
-
Go north and type
lookA note reads: Beacon panel code 42.Why The current room is a key inCLUES. -
Enter
panel 42in the WorkshopThe panel is at the Beacon.Why The location check runs first and the panel remains closed. -
Go east and enter
panel 99Wrong code. Check the Workshop clue.Why Pip is in the right room but the text differs from"42". -
Enter
panel 42Beacon panel open.Why The success branch storesTrueunder"panel_open".
Predict before you run What message appears if you type just panel at the Beacon with the panel closed?
Reveal the explanation
Wrong code. Check the Workshop clue. The parser gives it an empty string as the argument. The empty string and "42" are different, so the flag remains False.
Build the checkpoint
Python skills Boolean flags, Sequential conditions, Readable puzzle feedback.
1. Give the clue a place in the world
The Workshop note points to a short panel code. Keep clues together in a CLUES dictionary so you can add a clue without rewriting the command parser. The look function prints a note when the current room has an entry. Ask for look at Habitat and again at the Workshop to see the difference.
CLUES = {"Workshop": "A note reads: Beacon panel code 42."}
PANEL_CODE = "42"
2. Check location before the code
The code belongs to a panel at the Beacon. Check the room first and tell Pip where to go if someone runs panel 42 in the Workshop. At the Beacon, compare the typed text with PANEL_CODE. A wrong answer prompts the player to check the clue and keeps the flag unchanged.
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.")
3. Remember that the panel is open
Set panel_open to True after a correct answer. A flag records a fact another part of the program can read later. The new mission state begins with the flag set to False. In the next checkpoint, the repair action will read it as one of the conditions for restoring the beacon.
"panel_open": False,
"rescued": False,
}
Complete Python checkpoint · moonbase_17.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.")
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)
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–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–87
-
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
print("Moonbase Rescue") - Show the message or value in the output.
-
Line 77
look(state) - Run look with the supplied inputs and come back here when it returns.
-
Line 78
while True: - Repeat the indented work until a break, return or error ends this path.
-
Line 79
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 80
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 81
except EOFError: - Run this part only when the try block raises EOFError.
-
Line 82
print("Radio closed.") - Show the message or value in the output.
-
Line 83
break - Leave the nearest loop immediately and continue after it.
-
Line 85
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 86
if command == "quit": - Run the indented block only if this check is true.
-
Line 87
print("Mission paused.") - Show the message or value in the output.
Lines 88–100
-
Line 88
break - Leave the nearest loop immediately and continue after it.
-
Line 89
elif command == "look": - Run the indented block only if this check is true.
-
Line 90
look(state) - Run look with the supplied inputs and come back here when it returns.
-
Line 91
elif command == "status": - Run the indented block only if this check is true.
-
Line 92
show_status(state) - Run show_status with the supplied inputs and come back here when it returns.
-
Line 93
elif command == "go": - Run the indented block only if this check is true.
-
Line 94
move(state, argument) - Run move with the supplied inputs and come back here when it returns.
-
Line 95
elif command == "take": - Run the indented block only if this check is true.
-
Line 96
take(state, argument) - Run take with the supplied inputs and come back here when it returns.
-
Line 97
elif command == "panel": - Run the indented block only if this check is true.
-
Line 98
open_panel(state, argument) - Run open_panel with the supplied inputs and come back here when it returns.
-
Line 99
else: - Take this branch if the earlier checks for this decision were false.
-
Line 100
print("Unknown command.") - Show the message or value in the output.
Test the mission
- Open the panel using a clue you read in the Workshop.
- Try panel without a number to check that it receives a helpful response.
If something goes wrong
- A correct code fails after you change it.
- Match the clue and PANEL_CODE exactly. The comparison uses text, so leading zeroes count.
Mission extension
Design a fresh four-character code for this fictional panel. Change the note and code together, then test an older code and the new one.