Python 14 · Walk through the right door

Python lesson 14 of 50 · Early intermediate · About 35 minutes

Use Pip’s map to move north and east. Check that an unmarked direction leaves the rover safely in place.

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

Mission Use the current room’s exit dictionary to validate and apply movement.

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 the room. Look up Pip’s current location.. → Check the door. Read the destination with get.. → Move safely. Update the room after a valid direction..
Find the room → Check the door → Move safely

Understand the Python in this lesson

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

Send the direction to movement

When you type go north, the parser returns "go" and "north". The elif command == "go" branch passes the mission record and the second piece to move(state, argument). Inside the function those two inputs are called state and direction.

Read an exit through three layers

WORLD[state["room"]]["exits"] first finds Pip’s room name in the mission record. The middle lookup uses that name to find the room record in WORLD. The final lookup picks the room’s exit dictionary.

Ask whether a door exists

exits.get(direction) tries the typed direction as a key. If a door exists, it returns the destination room name. If the key is missing, get() returns None, Python’s special value for no result. Direct square-bracket lookup needs an existing key, so get() fits user input.

Guard the update

is None checks for that special result. A bare return ends this call to move() before the assignment below can run. The main loop can then ask for another command. With a real destination, the assignment changes state["room"] in the same dictionary the rest of the game reads.

How the pieces fit You have used a user command to change game state. Movement will now have a separate battery rule that can run only after a valid door has been found.

Follow one run, step by step
  1. Type go north from Habitat
    Pip arrives at the Workshop Why Habitat’s north door maps to Workshop, so the room value changes.
  2. Type go north again
    That direction has no exit here. Why Workshop has doors south and east. A missing direction ends the function early.
  3. Type go south
    Pip arrives at the Habitat Why The door lookup starts with Pip’s updated room.
  4. Type status
    Habitat | Energy: 8 | Cargo: empty Why This version changes the room on a successful move. Battery spending is added next.

Predict before you run After arriving in the Workshop, what will go with a blank direction do?

Reveal the explanation

The parser gives move() an empty string for the direction. There is no empty exit key, so get() gives None, the missing-door message appears, and Pip stays in the Workshop.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills Dictionary get, Early return, State transitions.

1. Read the current doors first

Start with Pip in the Habitat. Before you move, point to the north exit on your paper map and predict where it goes. In the move function, WORLD[state['room']]['exits'] picks the exit dictionary for Pip’s current room. A direction can be valid in one room and unavailable in another.

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
    state["room"] = destination
    print("Pip arrives at the", destination)

2. Check for a missing passage

The dictionary’s get method gives None when the direction is absent. Put the message and return inside that check. The function stops before it can write a new room name. Try an unmarked direction and use status afterwards to show that Pip stayed in the same place.

if destination is None:
        print("That direction has no exit here.")
        return
    state["room"] = destination
    print("Pip arrives at the", destination)

3. Connect the action and argument

The command parser splits go north into go and north. Call move with the second value. A legal move updates the room name and prints the arrival. Ask for look after the move and compare the description with the room you expected from the map.

elif command == "go":
        move(state, argument)
    else:
Complete Python checkpoint · moonbase_14.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"}},
}

state = {
    "room": "Habitat",
    "energy": 8,
    "parts": [],
    "rescued": False,
}

def look(state):
    room = state["room"]
    info = WORLD[room]
    print(info["scene"])
    print("Exits:", ", ".join(info["exits"]))

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
    state["room"] = destination
    print("Pip arrives at the", destination)

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)
    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–27
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.
Lines 8–13 state = { "room": "Habitat", "energy": 8, "parts": [], "rescued": False, }
Work out the value on the right, then store it in state. Each colon pairs a key with its value.
Line 15 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 16 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 17 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 18 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 19 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 21 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 22 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 23 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 25 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 26 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 27 if not words:
Run the indented block only if this check is true. The word not reverses which result counts as true.
Lines 28–42
Line 28 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 29 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 30 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 31 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 33 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 34 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 35 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 36 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 37 print("That direction has no exit here.")
Show the message or value in the output.
Line 38 return
Leave this function now.
Line 39 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 40 print("Pip arrives at the", destination)
Show the message or value in the output.
Line 42 print("Moonbase Rescue")
Show the message or value in the output.
Lines 43–56
Line 43 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 44 while True:
Repeat the indented work until a break, return or error ends this path.
Line 45 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 46 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 47 except EOFError:
Run this part only when the try block raises EOFError.
Line 48 print("Radio closed.")
Show the message or value in the output.
Line 49 break
Leave the nearest loop immediately and continue after it.
Line 51 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 52 if command == "quit":
Run the indented block only if this check is true.
Line 53 print("Mission paused.")
Show the message or value in the output.
Line 54 break
Leave the nearest loop immediately and continue after it.
Line 55 elif command == "look":
Run the indented block only if this check is true.
Line 56 look(state)
Run look with the supplied inputs and come back here when it returns.
Lines 57–62
Line 57 elif command == "status":
Run the indented block only if this check is true.
Line 58 show_status(state)
Run show_status with the supplied inputs and come back here when it returns.
Line 59 elif command == "go":
Run the indented block only if this check is true.
Line 60 move(state, argument)
Run move with the supplied inputs and come back here when it returns.
Line 61 else:
Take this branch if the earlier checks for this decision were false.
Line 62 print("Unknown command.")
Show the message or value in the output.

Test the mission

  • Go east from Habitat and ask for status. The room should be Greenhouse.
  • Return west. Check you are back at the Habitat.

If something goes wrong

Every direction uses the Habitat exits.
Read state['room'] inside move each time instead of storing the Habitat exit dictionary once.

Mission extension

Experiment with an additional linked room. Add a door into the room and a separate door back.