Python 15 · Spend battery power on real moves

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

Every hallway costs one battery unit. Build an energy rule that rewards planning and keeps invalid commands free.

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

Mission Check movement conditions before changing the battery or location.

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.

Validate the door. A dead end leaves Pip unchanged.. → Check the charge. Only a charged rover can move.. → Pay for the move. Spend one unit and update the room..
Validate the door → Check the charge → Pay for the move

Understand the Python in this lesson

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

Put checks before changes

move() looks up the destination first. If it is None, the function returns at once. The next check uses == to ask whether the battery value equals zero. An if block runs when its test is true, so this second check can stop a valid move when the battery is empty.

Read the short subtraction

state["energy"] -= 1 means read the stored value, subtract one and write the result back under the same key. In this checkpoint it gives the same result as the longer update from Lesson 11. The two checks come before that line. Pip pays one unit only when both checks allow the move.

Apply the cost and then move

The next assignment updates the room to the destination. The print line reads the destination name for the arrival message. All three statements are indented to belong to move() and align with each other outside the two if blocks. They run in that order when the guards have allowed the move.

Test right at zero

A boundary test checks exactly where the rule changes. Start with one unit and use a legal door. The energy becomes zero and Pip arrives. The next legal door triggers the empty-battery message before anything is subtracted or written.

How the pieces fit Only movement costs power. The game can now add supply gathering and puzzle commands that use the same mission record while leaving the battery alone.

Follow one run, step by step
  1. Start with energy 8 and enter go north
    Pip arrives at the Workshop, with energy 7. Why Habitat’s north door is valid and the battery guard passes.
  2. Try go north from Workshop
    That direction has no exit here. Why The first guard stops the command before it can spend energy.
  3. Type status
    Workshop | Energy: 7 | Cargo: empty Why Status reads the unchanged energy after the rejected direction.
  4. With energy 0 at Habitat, enter go north
    Pip has no energy left to move. Why The door exists, then the battery guard stops the move.

Predict before you run With energy 0 in the Workshop, which message does go north produce?

Reveal the explanation

That direction has no exit here. The door check runs first and returns because there is no north door. The battery check will be reached if you try a real door, such as south.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills Guard clauses, Subtraction assignment, Boundary testing.

1. Set the movement rule

Read through move before you edit. The function has to check that a door exists and that the rover has power. Keep the movement spending rule in one place so it applies whichever direction you choose. One battery unit is paid for each legal move. A status check or a wrong direction costs nothing.

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)

2. Put the checks before the changes

The method reads the destination first, then checks for an empty battery. Only after both checks does it reach state['energy'] -= 1. The shorthand subtracts one from the existing number. Follow it with the room update so the battery and room describe the same move.

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)

3. Test the very last unit

Spend the eight units by going north and south four times, staying on the nearby two-room route. Ask for status, then try another legal move. It should print the low-power response, keep the room unchanged and never show a negative battery. Repeat with an invalid exit first and count the legal moves again.

def show_status(state):
    cargo = ", ".join(state["parts"]) or "empty"
    print(f'{state["room"]} | Energy: {state["energy"]} | Cargo: {cargo}')
Complete Python checkpoint · moonbase_15.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
    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)

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–41
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 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 40 print("Pip has no energy left to move.")
Show the message or value in the output.
Line 41 return
Leave this function now.
Lines 42–56
Line 42 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Line 43 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 44 print("Pip arrives at the", destination)
Show the message or value in the output.
Line 46 print("Moonbase Rescue")
Show the message or value in the output.
Line 47 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 48 while True:
Repeat the indented work until a break, return or error ends this path.
Line 49 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 50 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 51 except EOFError:
Run this part only when the try block raises EOFError.
Line 52 print("Radio closed.")
Show the message or value in the output.
Line 53 break
Leave the nearest loop immediately and continue after it.
Line 55 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 56 if command == "quit":
Run the indented block only if this check is true.
Lines 57–66
Line 57 print("Mission paused.")
Show the message or value in the output.
Line 58 break
Leave the nearest loop immediately and continue after it.
Line 59 elif command == "look":
Run the indented block only if this check is true.
Line 60 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 61 elif command == "status":
Run the indented block only if this check is true.
Line 62 show_status(state)
Run show_status with the supplied inputs and come back here when it returns.
Line 63 elif command == "go":
Run the indented block only if this check is true.
Line 64 move(state, argument)
Run move with the supplied inputs and come back here when it returns.
Line 65 else:
Take this branch if the earlier checks for this decision were false.
Line 66 print("Unknown command.")
Show the message or value in the output.

Test the mission

  • With a fresh eight-unit battery, reach the Beacon in two moves.
  • Start with 1 energy and check that exactly one legal movement is possible.

If something goes wrong

An invalid direction uses energy.
Keep the subtraction after the missing-destination return.

Mission extension

Temporarily set the mission battery to 4 and draw a route that visits the Workshop, Greenhouse and Beacon in four moves.