← Reference

Errors and the adventure: cheat sheet

Deeper Python in the console · In any playground, open Reference to copy these.

int

Turn text made of digits, such as "12", into a whole number you can calculate with.

int(text)

write a file

"w" makes the file, or empties it first if it is already there, then writes. with closes the file at the end.

with open("save.txt", "w") as f:
    f.write(text)

save with json

Writes a dictionary or list to a file as JSON text.

import json

with open("game.json", "w") as f:
    json.dump(game, f)

a missing file

The first time, there is no file: catch FileNotFoundError instead of stopping.

try:
    with open("save.txt") as f:
        text = f.read()
except FileNotFoundError:
    print("There is no save yet.")

try and except

Run lines that might fail. If the named error happens, the except lines run instead of the program stopping.

try:
    n = int(text)
except ValueError:
    print("That is not a number.")

read a file

Opens the file to read and gives you all of it as one piece of text.

with open("save.txt") as f:
    text = f.read()

load with json

Reads JSON text back into the dictionary or list that was saved.

import json

with open("game.json") as f:
    game = json.load(f)