Use this reference when a Python instruction or symbol is new to you. Find the word or punctuation, read what it does in Moonbase Rescue, then follow the lesson link to see the surrounding code. The small examples are fragments from Pip’s programs. For a complete program, open the Python checkpoint in the lesson. Try reading each example aloud as an instruction before you run it.
Read from left to right on a line, then follow the indents. Try predicting one output, change one value, and run again. Some examples are fragments from a complete lesson.
Read your first instructions
print() and a call
A call asks a function to do its job. Put the information you want to give the function inside its parentheses. Here print writes one line to the output, so you can see that your program ran.
print("Moonbase Rescue")
See it in the course Lesson 1 · Lesson 20
Strings and quotes
A string is text in quotes. The quotes show where the text begins and ends. Both single and double quotes work if the two ends match. In the radio message, the colon is part of the text.
"Pip to Mission Control: habitat lights are on."
See it in the course Lesson 1
Names and assignment (=)
An assignment stores a value under a name. Python works out the expression on the right and gives its result to the name on the left. Read this aloud as “set rover to Pip”. Later, writing rover without quotes uses the stored value.
rover = "Pip"
See it in the course Lesson 2 · Lesson 10
Arguments and commas
A comma separates things you give to a function. Here the first argument is literal text and the second is the stored rover name. print adds one space between them in its usual form.
print("Rover:", rover)
See it in the course Lesson 2
Numbers, expressions and updates
A number written without quotes can take part in arithmetic. * multiplies. + adds. - subtracts. Python evaluates the right side before assigning the result, so this update uses the old energy value to work out the new one.
energy = energy - trip_cost
See it in the course Lesson 3
input() and a prompt
input displays its prompt, pauses for you to type and returns what you type as a string. The prompt can end with a space to make the answer easier to read. Even if you type digits, input gives you text.
destination = input("Send a station name: ")
See it in the course Lesson 4
f-strings and braces
An f before the opening quote lets Python evaluate what is inside { } and insert the result into the text. The braces in this example have a different job from braces surrounding a dictionary or a set.
print(f"{rover} received: {destination}.")
See it in the course Lesson 4
Text methods and the dot
A method is an operation attached to a value. The dot tells Python which value to use it on. strip takes away leading and trailing whitespace and lower returns lowercase text. Chaining calls passes the result from one call to the next.
choice = input("Destination: ").strip().lower()
See it in the course Lesson 5
Decisions, loops and the shape of code
Indentation, colons and blocks
A heading ending in : can introduce a block. Lines in that block begin farther from the left margin. Keep lines that belong together evenly indented. The line below the if only runs when its condition is true.
if choice == "workshop":
station = "Workshop"
See it in the course Lesson 5 · Lesson 6
if, elif and else
Python checks the if first and then checks each elif in order until one matches. It runs the matching block. else gives the remaining case. This elif only gets a turn if the earlier workshop condition was false.
elif choice == "greenhouse":
See it in the course Lesson 5
Comparisons (==, !=, <, <=, >, >=)
A comparison asks a question and gives True or False. == asks if values match, and != checks if they differ. The angle signs compare order or size. Use one = to assign a value.
if energy < cost:
See it in the course Lesson 9 · Lesson 10
Combining conditions (and, or, not)
and needs both checks to be true, or needs at least one, and not flips a yes into a no or a no into a yes. Here both checks describe a part Pip can see and still needs to collect.
if part is not None and part not in state["parts"]:
See it in the course Lesson 16 · Lesson 20
while and True
while rechecks a condition before every round. True is a Boolean value that stays true, so this loop uses a way out inside its block. Pip’s radio can keep waiting when a command is unclear.
while True:
See it in the course Lesson 6 · Lesson 40
break and continue
break leaves the nearest loop. continue jumps straight to its next check or round. In this fragment, a successful look command shows the display and skips the part of the turn that records a game action.
if command == "look":
show_state(state, locations, plain)
continue
See it in the course Lesson 41 · Lesson 50
for and range()
for gives a loop name each value in turn. range makes numbers to use in that loop. With range(3, 0, -1) the numbers are 3, 2 and 1. It stops before 0. The negative step makes the countdown go down.
for number in range(3, 0, -1):
See it in the course Lesson 8
Inline choices (yes if condition else no)
An inline choice is an expression that produces a value. Python checks the condition and then uses one of the two choices. Here a repaired beacon gives the word online. Everything else gives offline.
restored = "online" if state.rescued else "offline"
See it in the course Lesson 31 · Lesson 40
Compound assignment (-= and +=)
-= subtracts from the value already stored and keeps the result at the same place. += adds in the same way. This line spends exactly one unit by updating the energy entry after a move passes its checks.
state["energy"] -= 1
Organise the moonbase’s information
Lists and indexes
A list holds items in order inside square brackets. An index is an item’s position, counting from zero. toolkit[0] means the first tool. An out-of-range index is an error, so check the length if the item may be missing.
print(f"First tool: {toolkit[0]}.")
See it in the course Lesson 7
append() and remove()
append adds an item at the end of an existing list. remove finds and removes the first matching value. A list changes in place, so call append on the toolkit directly. Check for the item before you use remove.
toolkit.append(found)
See it in the course Lesson 7
Membership (in, not in)
in asks if something is present. For a list, it checks the values. For a dictionary, it checks the keys. not in checks for absence, so Pip can collect one of each repair part without counting a duplicate.
if part in state["parts"]:
See it in the course Lesson 16 · Lesson 20
Dictionaries and keys
A dictionary matches keys to values. Write each key and value with a colon between them. state["room"] reads the value under room. WORLD[state["room"]]["exits"] first finds the room’s record and then selects its exits.
exits = WORLD[state["room"]]["exits"]
See it in the course Lesson 14 · Lesson 20
get() and None
dictionary.get looks for a key and returns None by default when it cannot find it. None stands for a missing value. The next check can spot a direction with no exit and stop the move cleanly.
destination = exits.get(direction)
See it in the course Lesson 14 · Lesson 20
.items() and .values()
items gives each dictionary key paired with its value, so one pass can give you a room and its exits. values gives just the stored values, for example the list of what parts the player needs from each room.
for room, exits in WORLD.items():
See it in the course Lesson 33 · Lesson 40
Tuples and unpacking
A tuple keeps items together in order and cannot be changed one item at a time. Python can return several items together as a tuple. Two names on the left unpack two returned items in order, making the verb and its argument available separately.
command, argument = read_command(raw)
See it in the course Lesson 13 · Lesson 20
Sets and unique things
A set keeps each value once. The order has no role in a membership check. A visited set helps a route planner skip rooms it has already explored. In a validation check, set(parts) keeps one copy of each recorded part.
seen = {start}
See it in the course Lesson 35 · Lesson 50
issubset() and difference()
Required parts form a set. issubset checks whether all of them are in the player’s pack. difference can report which required parts are still missing, so the status message can give a clear next task.
if not REQUIRED.issubset(state.parts):
See it in the course Lesson 31 · Lesson 40
len(), split() and join()
len checks how many items are in a value. split can break typed commands into words. join does the opposite job for display by placing the chosen separator between strings. Together they help Pip read commands and report cargo.
cargo = ", ".join(state["parts"]) or "empty"
See it in the course Lesson 13 · Lesson 20
Indexes and slices in text
An index takes one character. A slice takes a piece of the text. In command[3:] the 3 is the starting index and there is no stop index, so Python keeps everything from index 3 to the end. This leaves the direction after go and its space.
direction = command[3:]
See it in the course Lesson 31 · Lesson 40
Comprehensions and generator expressions
A list comprehension builds a list from a for expression. An optional if filters the items. Generator expressions yield items one at a time for a consumer such as join, all or any. This list comprehension creates one legal movement command per exit.
actions = [f"go {room}" for room in LINKS[current.room]] + ["take", "repair"]
See it in the course Lesson 43 · Lesson 50
all() and any()
all is true when every item tested is true. any is true when at least one is true. Here the loop inside all checks membership once for each required part. not makes the whole condition true when Pip is still missing something.
elif not all(part in state["parts"] for part in ROOM_PARTS.values()):
See it in the course Lesson 18 · Lesson 20
next() and a fallback
next takes the first available result from an iterator. Give it a second argument if there might be no result. Here a generator checks which room holds each part and returns the first match. None means Pip found no matching part.
part = next((name for name, room in locations.items() if room == state.room), None)
See it in the course Lesson 41 · Lesson 50
Sorting, totals and biggest values
sorted makes an ordered list. sum adds numbers. Here it counts movement commands because each True counts as one and each False counts as zero. max can then keep the biggest total seen so far while Pip compares routes.
movement = sum(command.startswith("go ") for command in route)
See it in the course Lesson 49 · Lesson 50
zip() and dict()
zip pairs the first items together, then the second items, and so on. dict can build a dictionary from those pairs. This line pairs each named repair part with a different room chosen by the sampler.
return dict(zip(PARTS, rng.sample(rooms, k=len(PARTS))))
Put game rules into functions
def, parameters and arguments
def gives a reusable block a name. The parameter names inside the definition’s parentheses are the inputs it expects. When you call travel, Python gives its energy and cost parameters the two values you supply in that order.
def travel(energy, cost):
See it in the course Lesson 9 · Lesson 10
return and early exits
return sends a result back to the caller and ends that call. Here a guard returns the current energy if the move cannot be paid for. A different path below the guard returns a smaller value.
if energy < cost:
return energy
See it in the course Lesson 9 · Lesson 10
Defaults and keyword arguments
A parameter with = in a function definition has a value to use if that argument is left out. In a call, name=value gives one particular parameter a value explicitly. Here plain is optional and starts as False.
def show_state(state, locations, plain=False):
See it in the course Lesson 41 · Lesson 50
* and ** unpacking
A star can spread items into a new sequence. Two stars can collect extra named arguments in a dictionary or pass them onward as named arguments. Here **changes lets spend accept a new room, parts or another state field by name.
def spend(state, **changes):
See it in the course Lesson 36 · Lesson 40
Pure functions, transitions and side effects
A pure rule returns the same answer for the same inputs and leaves outside data alone. A transition such as step returns the next state and an explanation. Keep printing and typing around the rule so you can test it by calling it directly.
following, _ = step(current, action, locations)
See it in the course Lesson 43 · Lesson 50
Dispatch dictionaries
Functions can be stored as dictionary values. A dispatcher looks up the command and then calls the matching function. Fetching a function and calling it are separate jobs, with parentheses needed for the call.
action = ACTIONS.get(command)
See it in the course Lesson 19 · Lesson 20
lambda and a function used later
A lambda is a short function made from one expression. In the command table its job is to wait until called, then render the current state. The colon separates its inputs from its expression. Here there are no inputs to name.
"status": lambda: describe(state),
See it in the course Lesson 40
The main guard
When Python runs a file directly, __name__ is "__main__". This test starts the game in that case. When a test imports the file to borrow a function, the test can use it without starting the interactive game.
if __name__ == "__main__":
Tools, files and checks before loading
import and from ... import
An import brings code from a module into your program. import json gives you access through the module name, such as json.loads. A from import brings the named tool into the current file directly, as with Path here.
from pathlib import Path
See it in the course Lesson 25 · Lesson 50
Path and UTF-8
A Path represents a file location. read_text reads text, and write_text writes it. UTF-8 is a way of storing text that supports many alphabets. Using the same encoding to read and write keeps save text consistent.
data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
See it in the course Lesson 26 · Lesson 30
JSON, dumps() and loads()
JSON is a text format for data. dumps turns supported Python values into JSON text. loads reads JSON text and reconstructs data. An indent of 2 makes the save easier for a person to read. The program still checks whether that data makes sense.
temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
See it in the course Lesson 27 · Lesson 30
try and except
Put an operation that might fail in try. Name the errors you can handle in except. A missing save should produce a useful message and keep the current mission. Other unexpected errors can still show up with an explanation for debugging.
except FileNotFoundError:
See it in the course Lesson 27 · Lesson 30
raise, ValueError and validation
raise signals an error rather than letting the game continue with invalid data. The caller can catch ValueError and tell the player the save cannot be used. Validate the room, energy and parts before replacing the current mission.
raise ValueError("unknown room")
See it in the course Lesson 26 · Lesson 30
type(), isinstance(), is and is not
isinstance asks if a value belongs to a type or one of its subclasses. type(value) gives its exact type. is checks identity. The save uses a strict integer check so a Boolean or a string cannot pass for a battery number.
if type(seed) is not int or not 0 <= seed <= 9999:
See it in the course Lesson 44 · Lesson 50
with, file modes and bounded reading
with takes care of closing a file after its block. rb says to read bytes. Reading just one byte beyond the allowed limit is enough to tell whether the save is too large, before asking the JSON reader to decode it.
with SAVE_FILE.open("rb") as stream:
payload = stream.read(SIZE_LIMIT + 1)
See it in the course Lesson 44 · Lesson 50
Temporary files and replace()
Write the new save to a temporary file first. Then replace the old save using that completed file. If writing fails first, the old save remains available. The temporary file has a different name so there is no need to erase the old save before writing.
temporary.replace(SAVE_FILE)
See it in the course Lesson 27 · Lesson 50
EOFError and end of input
If input reaches the end of the stream, Python raises EOFError. Catching it tells the game that there are no more radio commands coming. It can finish that turn or leave the input loop gracefully.
except EOFError:
State, route planning and repeatable missions
Dataclasses, fields and type annotations
A dataclass creates a class that holds named fields. Field names describe which facts go together in one mission state. A colon followed by a type is a type hint. A value after = is the default. Python does not usually check a field’s type just because you wrote its hint.
@dataclass(frozen=True)
class State:
See it in the course Lesson 31 · Lesson 50
Frozen data and replace()
frozen=True prevents regular assignment to dataclass fields. replace makes a new dataclass object with the requested changes, leaving the old state available for comparisons and replays. This call updates the room of the new state.
return replace(state, room=target), f"Arrived at {target}."
See it in the course Lesson 31 · Lesson 35
deque and popleft()
A deque is a queue you can add to at one end and take from at the other. popleft takes the oldest waiting item. The route planner stores a location and its moves together and explores the earliest waiting route next.
room, moves = queue.popleft()
See it in the course Lesson 35 · Lesson 40
Breadth-first search
Breadth-first search explores routes in layers. It tries the one-step options before the two-step ones, and marks states already seen. When every step counts the same, the first successful path it finds uses the fewest steps.
queue.append((neighbour, (*moves, direction)))
See it in the course Lesson 35 · Lesson 40
Random seeds and sampling
A seed sets the starting point of a random generator. Reusing it with the same rules makes a mission layout repeatable, which helps you give someone the same puzzle or reproduce a bug. Sampling without replacement selects different rooms.
return dict(zip(PARTS, rng.sample(rooms, k=len(PARTS))))
See it in the course Lesson 42 · Lesson 50
Replay from an action log
A replay starts from the same setup and applies the saved commands in order. It uses the game rules again and records the results. That lets you revisit the turn where something went wrong or verify a complete rescue.
def replay(commands):
See it in the course Lesson 37 · Lesson 40
Caching route results
A cache remembers a result so a repeated question with the same inputs can reuse it. This decorator remembers up to 16 recent sets of route inputs. Clear the cache before a fresh comparison and when a changed map would make old answers wrong.
@lru_cache(maxsize=16)
See it in the course Lesson 38 · Lesson 40
Profiling and cumulative time
Profiling counts calls and records how long work takes. The cumulative report includes time in a function and in the functions it calls. Compare a repeatable set of moves or hints before deciding which code is worth improving.
pstats.Stats(profiler).sort_stats("cumulative").print_stats(5)
Try, test and debug
Assertions and expected results
assert checks a rule you expect to be true. A failed assertion raises an error you can investigate. The rescue tests use assertions to check that Pip finishes successfully, keeps non-negative energy and has one trace entry for each action.
assert end.rescued and end.energy >= 0 and len(trace) == len(route)
See it in the course Lesson 46 · Lesson 50
unittest and test cases
unittest organises repeatable checks into methods in a TestCase class. Use assertEqual to compare results, assertTrue or assertFalse for a condition, and assertRaises for an error you expect. These checks tell you exactly which rule failed.
class MissionTests(unittest.TestCase):
See it in the course Lesson 29 · Lesson 40
Boundary tests
A boundary test tries the exact edge of an allowed range, then one value beyond it. For starting energy, check 5 and 15 are accepted and try 4 and 16 to check the rejection. This assertion from the audit guards another boundary, the most moves a low-energy route can use.
assert movement <= 5
See it in the course Lesson 49 · Lesson 50
End-to-end and regression tests
An end-to-end test follows the whole mission instead of checking one rule in isolation. A regression test repeats a case that used to fail so it cannot quietly break again. The campaign checks full rescues and the behaviour of bad commands.
assert step(start, "go beacon", locations)[0] == start
See it in the course Lesson 46 · Lesson 50
Trace and locate a problem
Print a meaningful value at the point where it might change, then repeat the smallest set of commands that produces the problem. A route status message showing room, turns and rescued can help you tell whether the move or only the display changed.
print(f"Replay: room={state.room}, turns={state.turns}, rescued={state.rescued}.")
See it in the course Lesson 37 · Lesson 40
SystemExit and test status
A terminal program can finish with a status for other tools. This expression chooses 0 for a successful test run and 1 when a test failed. raise SystemExit passes that status back to the terminal.
raise SystemExit(0 if result.wasSuccessful() else 1)
See it in the course Lesson 29 · Lesson 30
Command-line options and argparse
Command-line options are words or values you type after the program’s filename. argparse can read them, check their types and show help. Here --plain is a switch, so it is false by default and becomes true if you include the option.
parser.add_argument("--plain", action="store_true", help="use spoken-style status labels")