Python 26 · Load progress after checking it

Python lesson 26 of 50 · Intermediate · About 30 minutes

Reopen a mission without allowing an old or edited file to put Pip in a room that does not exist.

Pip presses a control in front of three mint-green mission screens.

Mission Validate the four saved fields before replacing the current game state.

Get ready

Read this as the next checkpoint in Pip’s mission. You can also start with the complete program below.

Save the complete checkpoint below as moonbase_26.py in a project folder and run python moonbase_26.py from that folder. Use python3 on systems where that is the Python 3 command. Use Python 3.10 or newer.

Read a candidate. Decode the file before touching the game.. → Validate. Check structure, types and relationships.. → Restore or keep. Replace state only when every check passes..
Read a candidate → Validate → Restore or keep

Understand the Python in this lesson

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

Read the file before changing the mission

SAVE_FILE.read_text(encoding="utf-8") reads the save into a string. json.loads(...) decodes that string into Python values. The result belongs to the temporary name data first. A file can contain valid JSON and still give Pip impossible game values.

Check the container and its keys

type(data) is not dict looks for exactly the dictionary type. set(data) makes a set of the dictionary’s keys, so the next check can compare names without caring about their order. or stops once one side is true, so Python does not need to inspect the set of keys if the container is already wrong.

Check the value and its type

type(data["energy"]) is not int rejects values such as True and "7". The comparison 0 <= data["energy"] <= 8 means the value must be at least zero and at most eight. The room must both be a string and be a known key in WORLD.

Check all the parts and the rescue flag

any(... for p in parts) looks at the parts one at a time and stops if one entry is a wrong type or unknown name. A set only keeps unique values, so different lengths for parts and set(parts) reveal a duplicate. A rescued game must have a true boolean flag and satisfy the same can_repair rule used during play.

Return either a checked record or the current one

raise ValueError(...) sends a problem to the caller when a check fails. except (OSError, ValueError): handles either of those types in this version. load_game always returns a state and a message. state, message = load_game(state) unpacks them so the radio can replace progress only after a successful check.

How the pieces fit Keep file loading in two steps. First decode the saved text. Then check whether the result makes sense to the moonbase rules. Keeping current nearby allows the radio to continue normally when either step fails.

Follow one run, step by step
  1. Go east, take the Coil and enter save.
    The file records Workshop, energy 7 and parts ["Coil"]. Why The file captures the state when save runs.
  2. Go west.
    The live game now has Habitat and energy 6. Why An ordinary move changes the current dictionary and spends energy.
  3. Enter load, then look.
    Saved progress loaded. The radio reports Workshop, energy 7 and Coil. Why Both the JSON decode and the game-specific checks succeeded.

Predict before you run Would an edited JSON file with energy set to true pass the check?

Reveal the explanation

It decodes to the Python boolean True. The exact type check rejects it, load_game returns the current state, and the radio reports Save unavailable; current progress kept.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills json.loads, validation, types, ValueError.

1. Read data into a separate value

Start with the same local folder as the previous lesson. The load function reads the save file as UTF-8 text and uses json.loads to decode it. Keep the current state available while you check the decoded value. A readable JSON file can still describe an impossible game.

def load_game(current):
    try:
        data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
        return validate_save(data), "Saved progress loaded."
    except (OSError, ValueError):
        return current, "Save unavailable; current progress kept."

2. Make a small checklist for valid progress

Require four keys, a known room, reasonable energy, and a list of legal parts with no duplicates. Check that the rescue flag is a real boolean and matches a successful repair. The energy check uses type(value) is int because Python treats booleans as integers in some checks. Raise ValueError when an entry breaks a rule.

def validate_save(data):
    if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}:
        raise ValueError("expected four state fields")
    if type(data["room"]) is not str or data["room"] not in WORLD:
        raise ValueError("unknown room")
    if type(data["energy"]) is not int or not 0 <= data["energy"] <= 8:
        raise ValueError("bad energy")
    parts = data["parts"]

3. Replace the live state only on success

The load function returns a pair of values. A valid save returns the new dictionary and confirmation. A bad or missing save returns the old dictionary and a short message. Run two sessions to observe a restoration. On the first, collect a part and save. On the second, make one move, load, and use look to verify all fields returned.

if verb == "load":
            state, message = load_game(state)
            print(message)
            continue
        print(apply(state, verb, argument))

4. Keep one good comparison

Make one save and note the room and charge before changing anything. Reopen it unchanged first so you know loading works. Only then try a missing field or extreme energy value in a separate copy. That order helps you tell a new validator bug from a problem in the test data.

Complete Python checkpoint · moonbase_26.py
import json
from pathlib import Path


WORLD = {
    "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None},
    "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"},
    "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"},
    "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None},
}
REQUIRED = {"Coil", "Cell"}
SAVE_FILE = Path("moonbase-save.json")


def new_mission():
    return {"room": "Habitat", "energy": 8, "parts": [], "rescued": False}


def can_repair(room, parts):
    return room == "Beacon" and REQUIRED.issubset(parts)


def describe(state):
    room, energy, cargo, _ = mission_snapshot(state)
    exits = ", ".join(WORLD[room]["exits"])
    parts = ", ".join(cargo) or "none"
    return f"{room} | energy {energy} | parts {parts} | exits {exits}"


def collect(state):
    item = WORLD[state["room"]]["part"]
    if item is None:
        return "There is no repair part here."
    if item in state["parts"]:
        return f"You already have the {item}."
    state["parts"].append(item)
    return f"Collected the {item}."


def repair(state):
    if can_repair(state["room"], state["parts"]):
        state["rescued"] = True
        return "Beacon restored! Pip has sent the rescue signal."
    return "Bring the Coil and the Cell to the Beacon."


def move(state, direction):
    destination = WORLD[state["room"]]["exits"].get(direction)
    if destination is None:
        return "That route is blocked."
    if state["energy"] == 0:
        return "Pip is out of energy."
    state["room"] = destination
    state["energy"] -= 1
    return f"Moved to {destination}."


def parse_command(text):
    words = text.lower().split()
    if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
        return "go", words[0]
    if len(words) == 2 and words[0] == "go":
        return "go", words[1]
    if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save", "load"}:
        return words[0], ""
    return "", ""


def save_game(state):
    SAVE_FILE.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
    return "Progress saved to moonbase-save.json."


def validate_save(data):
    if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}:
        raise ValueError("expected four state fields")
    if type(data["room"]) is not str or data["room"] not in WORLD:
        raise ValueError("unknown room")
    if type(data["energy"]) is not int or not 0 <= data["energy"] <= 8:
        raise ValueError("bad energy")
    parts = data["parts"]
    if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in parts):
        raise ValueError("unknown part")
    if len(parts) != len(set(parts)):
        raise ValueError("duplicate part")
    if type(data["rescued"]) is not bool:
        raise ValueError("bad rescue flag")
    if data["rescued"] and not can_repair(data["room"], parts):
        raise ValueError("inconsistent rescue")
    return data


def load_game(current):
    try:
        data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
        return validate_save(data), "Saved progress loaded."
    except (OSError, ValueError):
        return current, "Save unavailable; current progress kept."


def mission_snapshot(state):
    return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]


def apply(state, verb, argument):
    if verb == "look":
        return describe(state)
    if verb == "go":
        return move(state, argument)
    if verb == "take":
        return collect(state)
    if verb == "repair":
        return repair(state)
    return "Unknown command."


def run():
    state = new_mission()
    print("Moonbase Rescue | Pip on duty")
    print(describe(state))
    print("Try look, go, take, repair or quit.")
    while not state["rescued"]:
        try:
            raw = input("Pip> ")
        except EOFError:
            print("Radio closed.")
            break
        verb, argument = parse_command(raw)
        if verb == "quit":
            print("Pip is on standby.")
            break
        if verb == "save":
            print(save_game(state))
            continue
        if verb == "load":
            state, message = load_game(state)
            print(message)
            continue
        print(apply(state, verb, argument))


if __name__ == "__main__":
    run()

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–26
Line 1 import json
Bring in json. Its module name gives you access to the tools it contains.
Line 2 from pathlib import Path
Bring Path into this file from pathlib. These names can now be used directly.
Lines 5–10 WORLD = { "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None}, "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"}, "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"}, "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 11 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 12 SAVE_FILE = Path("moonbase-save.json")
Work out the value on the right, then store it in SAVE_FILE. Represent a file location so the program can work with it.
Line 15 def new_mission():
Define new_mission, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 16 return {"room": "Habitat", "energy": 8, "parts": [], "rescued": False}
Leave this function now and hand the result back to the line that called it. Each colon pairs a key with its value.
Line 19 def can_repair(room, parts):
Define can_repair, a reusable piece of the program. Its input names are room, parts. The indented body runs when something calls it.
Line 20 return room == "Beacon" and REQUIRED.issubset(parts)
Leave this function now and hand the result back to the line that called it. With and, every check must be true. Check whether every item in this set appears in the other collection.
Line 23 def describe(state):
Define describe, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 24 room, energy, cargo, _ = mission_snapshot(state)
Give each returned value to the matching name, from left to right. Run mission_snapshot with the supplied inputs and come back here when it returns.
Line 25 exits = ", ".join(WORLD[room]["exits"])
Work out the value on the right, then store it in exits. 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 parts = ", ".join(cargo) or "none"
Work out the value on the right, then store it in parts. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Lines 27–43
Line 27 return f"{room} | energy {energy} | parts {parts} | exits {exits}"
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 30 def collect(state):
Define collect, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 31 item = WORLD[state["room"]]["part"]
Work out the value on the right, then store it in item. The brackets look up a dictionary key or a position that starts at zero.
Line 32 if item 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 33 return "There is no repair part here."
Leave this function now and hand the result back to the line that called it.
Line 34 if item 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 35 return f"You already have the {item}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 36 state["parts"].append(item)
Add the value to the end without replacing the earlier entries.
Line 37 return f"Collected the {item}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 40 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 41 if can_repair(state["room"], state["parts"]):
Run the indented block only if this check is true. Run can_repair with the supplied inputs and come back here when it returns. The brackets look up a dictionary key or a position that starts at zero.
Line 42 state["rescued"] = True
Work out the value on the right, then store it in state["rescued"].
Line 43 return "Beacon restored! Pip has sent the rescue signal."
Leave this function now and hand the result back to the line that called it.
Lines 44–60
Line 44 return "Bring the Coil and the Cell to the Beacon."
Leave this function now and hand the result back to the line that called it.
Line 47 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 48 destination = WORLD[state["room"]]["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 49 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 50 return "That route is blocked."
Leave this function now and hand the result back to the line that called it.
Line 51 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 52 return "Pip is out of energy."
Leave this function now and hand the result back to the line that called it.
Line 53 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 54 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Line 55 return f"Moved to {destination}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 58 def parse_command(text):
Define parse_command, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 59 words = text.lower().split()
Work out the value on the right, then store it in words. Return a lowercase copy so capital letters do not change a command. Separate the string into a list of pieces.
Line 60 if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Lines 61–77
Line 61 return "go", words[0]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 62 if len(words) == 2 and words[0] == "go":
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. The brackets look up a dictionary key or a position that starts at zero.
Line 63 return "go", words[1]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 64 if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save", "load"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Line 65 return words[0], ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 66 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 69 def save_game(state):
Define save_game, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 70 SAVE_FILE.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
Write text to the file using the chosen encoding. Turn Python data into JSON text. This step does not write a file.
Line 71 return "Progress saved to moonbase-save.json."
Leave this function now and hand the result back to the line that called it.
Line 74 def validate_save(data):
Define validate_save, a reusable piece of the program. Its input names are data. The indented body runs when something calls it.
Line 75 if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}:
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. Find the exact type of this value.
Line 76 raise ValueError("expected four state fields")
Stop this path and report ValueError("expected four state fields") to whoever called this code.
Line 77 if type(data["room"]) is not str or data["room"] not in WORLD:
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. Find the exact type of this value.
Lines 78–90
Line 78 raise ValueError("unknown room")
Stop this path and report ValueError("unknown room") to whoever called this code.
Line 79 if type(data["energy"]) is not int or not 0 <= data["energy"] <= 8:
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. Find the exact type of this value.
Line 80 raise ValueError("bad energy")
Stop this path and report ValueError("bad energy") to whoever called this code.
Line 81 parts = data["parts"]
Work out the value on the right, then store it in parts. The brackets look up a dictionary key or a position that starts at zero.
Line 82 if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in parts):
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. Find the exact type of this value.
Line 83 raise ValueError("unknown part")
Stop this path and report ValueError("unknown part") to whoever called this code.
Line 84 if len(parts) != len(set(parts)):
Run the indented block only if this check is true. Count the characters or items. Collect distinct values, with no duplicate entries.
Line 85 raise ValueError("duplicate part")
Stop this path and report ValueError("duplicate part") to whoever called this code.
Line 86 if type(data["rescued"]) is not bool:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value. The brackets look up a dictionary key or a position that starts at zero.
Line 87 raise ValueError("bad rescue flag")
Stop this path and report ValueError("bad rescue flag") to whoever called this code.
Line 88 if data["rescued"] and not can_repair(data["room"], parts):
Run the indented block only if this check is true. 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 89 raise ValueError("inconsistent rescue")
Stop this path and report ValueError("inconsistent rescue") to whoever called this code.
Line 90 return data
Leave this function now and hand the result back to the line that called it.
Lines 93–109
Line 93 def load_game(current):
Define load_game, a reusable piece of the program. Its input names are current. The indented body runs when something calls it.
Line 94 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 95 data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
Work out the value on the right, then store it in data. Read JSON text or bytes and turn it back into Python data. Read a file and decode its contents into text.
Line 96 return validate_save(data), "Saved progress loaded."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run validate_save with the supplied inputs and come back here when it returns.
Line 97 except (OSError, ValueError):
Run this part only when the try block raises (OSError, ValueError).
Line 98 return current, "Save unavailable; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 101 def mission_snapshot(state):
Define mission_snapshot, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 102 return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero. Collect ordered items in a tuple, whose entries cannot be reassigned.
Line 105 def apply(state, verb, argument):
Define apply, a reusable piece of the program. Its input names are state, verb, argument. The indented body runs when something calls it.
Line 106 if verb == "look":
Run the indented block only if this check is true.
Line 107 return describe(state)
Leave this function now and hand the result back to the line that called it. Run describe with the supplied inputs and come back here when it returns.
Line 108 if verb == "go":
Run the indented block only if this check is true.
Line 109 return move(state, argument)
Leave this function now and hand the result back to the line that called it. Run move with the supplied inputs and come back here when it returns.
Lines 110–124
Line 110 if verb == "take":
Run the indented block only if this check is true.
Line 111 return collect(state)
Leave this function now and hand the result back to the line that called it. Run collect with the supplied inputs and come back here when it returns.
Line 112 if verb == "repair":
Run the indented block only if this check is true.
Line 113 return repair(state)
Leave this function now and hand the result back to the line that called it. Run repair with the supplied inputs and come back here when it returns.
Line 114 return "Unknown command."
Leave this function now and hand the result back to the line that called it.
Line 117 def run():
Define run, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 118 state = new_mission()
Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
Line 119 print("Moonbase Rescue | Pip on duty")
Show the message or value in the output.
Line 120 print(describe(state))
Show the message or value in the output. Run describe with the supplied inputs and come back here when it returns.
Line 121 print("Try look, go, take, repair or quit.")
Show the message or value in the output.
Line 122 while not state["rescued"]:
Check not state["rescued"] before each pass. Repeat the indented work while it is true.
Line 123 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 124 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.
Lines 125–137
Line 125 except EOFError:
Run this part only when the try block raises EOFError.
Line 126 print("Radio closed.")
Show the message or value in the output.
Line 127 break
Leave the nearest loop immediately and continue after it.
Line 128 verb, argument = parse_command(raw)
Give each returned value to the matching name, from left to right. Run parse_command with the supplied inputs and come back here when it returns.
Line 129 if verb == "quit":
Run the indented block only if this check is true.
Line 130 print("Pip is on standby.")
Show the message or value in the output.
Line 131 break
Leave the nearest loop immediately and continue after it.
Line 132 if verb == "save":
Run the indented block only if this check is true.
Line 133 print(save_game(state))
Show the message or value in the output. Run save_game with the supplied inputs and come back here when it returns.
Line 134 continue
Skip the rest of this pass and start the next loop check.
Line 135 if verb == "load":
Run the indented block only if this check is true.
Line 136 state, message = load_game(state)
Give each returned value to the matching name, from left to right. Run load_game with the supplied inputs and come back here when it returns.
Line 137 print(message)
Show the message or value in the output.
Lines 138–143
Line 138 continue
Skip the rest of this pass and start the next loop check.
Line 139 print(apply(state, verb, argument))
Show the message or value in the output. Run apply with the supplied inputs and come back here when it returns.
Line 142 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 143 run()
Run run with the supplied inputs and come back here when it returns.

Test the mission

  • Type east, take, save, quit.
  • Start again, type load, look, quit and check you are back in Workshop.
  • Try load in a fresh folder. It should say current progress was kept.

If something goes wrong

The save will not load after a hand edit.
Check the keys, value types, room names, energy and unique part names. Test with a fresh game-generated save.

Mission extension

Write a second validation example: change the energy to 99 in a copy of your own save and observe the safe response.