Python guide

The language you write in: every idea of the course, with examples and what they print.29 topics
How the game works: the Code Kingdom guide

Every idea of the course, short and simple: what it is, an example and what it prints, how it works in the game, and where to practise it.

Part 1

Foundations

From one command to a villager that loops and decides: commands, loops, values, while, decisions, numbers and text.

1.1

Commands

Practise it in Code Kingdom 1-1

A program is a list of commands that run one after another, from the top.

Python reads your script line by line, top to bottom, and does what each line says. A command is a name followed by brackets: print("Hi"). What's inside the brackets tells the command what to work with.

Your units in the game have commands of their own. Write me. (the unit running the script), then the command: me.move("right").

print("Hello, island!")
print("I am", 10, "years old")
print(3 + 4)
Output
Hello, island!
I am 10 years old
7

In the game

Three steps to the right, then a hello:

me.move("right")
me.move("right")
me.move("right")
me.say("Hello!")

Watch out: Python cares about spelling and capital letters: Print("Hi") is an error, print("Hi") works. Text always goes in quotes.

1.2

Loops

Practise it in Code Kingdom 1-10

A loop runs the same lines again and again, so you don't have to write them twice.

for i in range(3): runs the lines under it 3 times, while i counts 0, 1, 2. The lines that belong to the loop are indented: moved 4 spaces to the right.

A line that isn't indented isn't part of the loop: it runs once, after the loop is done. A loop can hold another loop, and then the inner one runs all its rounds for every round of the outer one.

for i in range(3):
    print("Step", i)
print("Done!")
Output
Step 0
Step 1
Step 2
Done!

In the game

Four steps to the right, then three swings of the axe:

for i in range(4):
    me.move("right")
for i in range(3):
    me.harvest()

Watch out: Don't forget the : at the end of the for line, and indent every line that should repeat.

1.3

Variables

Practise it in Code Kingdom 1-19

A variable is a name for a value, so your program can remember it.

= puts a value into a name: wood = 5 means from now on, wood is 5. Use the name, and Python uses its value. You can change it any time, even with its own old value: wood = wood + 3.

Values come in kinds: whole numbers (5), numbers with a point (2.5), text in quotes ("Ada"), and True or False.

name = "Ada"
wood = 5
wood = wood + 3
print(name, "has", wood, "wood")
Output
Ada has 8 wood

In the game

A villager remembers the tree it's chopping, so it can go back to it:

tree = me.nearest("tree")
me.go_to(tree)
me.harvest(tree)

Watch out: = isn't the equals of maths: it stores a value. To ask whether two things are equal, use ==.

1.4

While loops

Practise it in Code Kingdom 1-26

while repeats some lines as long as something is true.

while asks a question before every round, like if does. While the answer is True, the indented lines run again; once it's False, the program goes on below the loop.

while True: never stops by itself: that's how a unit keeps working for ever. A loop that should stop must change what it asks about: count = count - 1, one step closer to the shore, a fuller backpack.

count = 3
while count > 0:
    print(count)
    count = count - 1
print("Go!")
Output
3
2
1
Go!

In the game

Walk to the shore, then chop trees for ever:

while me.look("right") == "grass":
    me.move("right")

while True:
    me.go_to(me.nearest("tree"))
    me.harvest()

Watch out: If nothing inside the loop changes the answer, the loop never ends. Make sure every round brings it closer to stopping.

1.5

Decisions

Practise it in Code Kingdom 1-32

if runs some lines only when something is true.

After if comes a question that's either True or False, then :. The indented lines run only when the answer is True. else: runs when it isn't, and elif (else if) asks another question.

Questions compare things: == equal, != not equal, < smaller, > bigger, <= and >=. Join them with and, or and not.

wood = 12
if wood >= 10:
    print("Enough for a house!")
elif wood > 0:
    print("Keep chopping")
else:
    print("No wood at all")
Output
Enough for a house!

In the game

Look before you leap:

if game.look(me.x + 1, me.y) == "water":
    me.say("Not that way!")
else:
    me.move("right")

Watch out: Compare with ==, not =. And only one branch of an if, elif, else runs: the first one whose question is True.

1.6

Numbers and maths

Practise it in Code Kingdom 1-44

Python is a calculator, with a few clever extras.

+, -, * (times) and / (divided by) work like in maths, and brackets go first. / always gives a number with a point: 7 / 2 is 3.5.

To share things out, // says how many whole times one number fits into another, and % what's left over: 7 apples for 2 friends is 7 // 2, 3 each, and 7 % 2, 1 left. ** is to the power of, round() rounds and abs() drops the minus sign.

print(7 / 2)
print(7 // 2, 7 % 2)
print(2 ** 3)
print(round(3.7), abs(-5))
Output
3.5
3 1
8
4 5

In the game

How many steps is it to the castle?

dx = abs(game.castle.x - me.x)
dy = abs(game.castle.y - me.y)
me.say("Steps home:", dx + dy)

Watch out: / gives 2.0, not 2. When you need a whole number (like a number of steps), use //.

1.7

Text (strings)

Practise it in Code Kingdom 1-52

Text in quotes is called a string: you can join it, cut it, search it and fill it in.

+ joins strings together and * repeats them. len() counts the letters. Every letter has a number for its place, starting from 0: word[0] is the first, word[-1] the last, and word[1:4] cuts out the letters from place 1 up to (not including) 4.

An f-string fills values in for you: f"I have {wood} wood". Strings have commands of their own too: .upper(), .lower(), .strip(), .replace() and .split().

word = "python"
print(word.upper(), len(word))
print(word[0], word[-1], word[1:4])
wood = 5
print(f"I have {wood} wood")
print("ho" * 3)
Output
PYTHON 6
p n yth
I have 5 wood
hohoho

In the game

A unit tells you what it's carrying:

me.say(f"{me.name} carries {me.load}")

Watch out: Numbers and strings don't mix with +: "Wood: " + 5 is an error. Use an f-string, or str(5).

Part 2

Data

Keeping many things at once: lists, dictionaries, tuples, sets, comprehensions and match.

2.1

Lists

Practise it in Code Kingdom 2-1

A list keeps many values in order, in one variable.

Write a list in square brackets: path = ["up", "up", "left"]. len(path) counts what's in it, path[0] is the first item (counting from 0 again), and .append() adds one at the end.

for goes through a list one item at a time: for step in path:. A list can hold anything: numbers, strings, even every tree on the island.

path = ["up", "up", "left"]
path.append("down")
print(len(path), path[0], path[-1])
for step in path:
    print("Go", step)
Output
4 up down
Go up
Go up
Go left
Go down

In the game

Walk a path written as a list:

for step in ["up", "up", "left", "down"]:
    me.move(step)
print(len(game.trees), "trees on the island")

Watch out: In a list of 3, the last one is [2]: asking for [3] is an IndexError.

2.2

Dictionaries

Practise it in Code Kingdom 2-13

A dictionary looks values up by a name, like words in a real dictionary.

Write one in curly brackets, as pairs of a key and its value: bag = {"wood": 3, "gold": 1}. Then bag["wood"] is 3, and bag["meat"] = 2 adds a new pair.

.get(key, default) gives the default when the key isn't there, and for key, value in bag.items(): goes through every pair.

bag = {"wood": 3, "gold": 1}
bag["wood"] = bag["wood"] + 2
bag["meat"] = 4
print(bag["wood"], bag.get("fish", 0))
for item, amount in bag.items():
    print(item, amount)
Output
5 0
wood 5
gold 1
meat 4

In the game

The castle's stock is a dictionary:

if game.stock["wood"] >= 30:
    me.say("We can build a house!")

Watch out: Asking for a key that isn't there, like bag["fish"], is a KeyError. Check with in first, or use .get().

2.3

Tuples

Practise it in Code Kingdom 2-25

A tuple is a few values that belong together, like a position (x, y).

Write a tuple in round brackets: spot = (3, 5). It's like a list that can't be changed. Unpacking gives each value its own name: x, y = spot, and it even swaps two values in one line: a, b = b, a.

enumerate() gives you every item together with its number, and zip() walks two lists side by side.

spot = (3, 5)
x, y = spot
print(x, y)
a, b = 1, 2
a, b = b, a
print(a, b)
for i, name in enumerate(["Ada", "Ben"]):
    print(i, name)
Output
3 5
2 1
0 Ada
1 Ben

In the game

Every position on the island is a tuple:

x, y = me.position
me.go_to((x + 3, y))

Watch out: A tuple can't be changed: spot[0] = 4 is an error. Make a new one instead: spot = (4, 5).

2.4

Sets

Practise it in Code Kingdom 2-31

A set keeps just one of each thing, and quickly tells you whether something is in it.

Write a set in curly brackets, without pairs: {1, 2, 3}, or start an empty one with set(). Adding something it already has changes nothing, so a set is perfect for remembering where you've been.

Sets can be compared: a & b is what both have, a | b is everything in either, and a - b is what a has and b doesn't.

seen = set()
for spot in [(1, 1), (1, 2), (1, 1)]:
    seen.add(spot)
print(len(seen))
a = {1, 2, 3}
b = {2, 3, 4}
print(sorted(a & b), sorted(a | b), sorted(a - b))
Output
2
[2, 3] [1, 2, 3, 4] [1]

In the game

Remember every tile you've stood on:

visited = set()
for step in ["right", "right", "left", "down"]:
    me.move(step)
    visited.add(me.position)
me.say(len(visited), "different tiles")

Watch out: A set has no order and no places: seen[0] doesn't work. And {} is an empty dictionary, not a set: use set().

2.5

Comprehensions

Practise it in Code Kingdom 2-37

Build a whole list in one line, from a recipe for what goes in it.

[n * 2 for n in numbers] makes a new list with every number doubled. Add an if to keep only some: [n for n in numbers if n > 2]. Curly brackets make a dictionary the same way.

They go well with a few helpers: sum() adds everything up, any() asks is at least one True?, all() asks are they all True?, and sorted() puts things in order.

numbers = [1, 2, 3, 4, 5]
print([n * 2 for n in numbers])
print([n for n in numbers if n % 2 == 0])
print(sum(numbers))
print(any(n > 4 for n in numbers), all(n > 0 for n in numbers))
squares = {n: n * n for n in range(1, 4)}
print(squares)
Output
[2, 4, 6, 8, 10]
[2, 4]
15
True True
{1: 1, 2: 4, 3: 9}

In the game

Only the gold rocks with plenty left:

rich = [rock for rock in game.gold_mines if rock.amount > 5]
me.say(len(rich), "rich gold rocks")

Watch out: When a comprehension gets hard to read, a plain for loop does the same job just as well.

2.6

match and case

Practise it in Code Kingdom 2-44

match compares one value with patterns, and runs the first one that fits.

It's a tidy way to write a long if, elif, elif... Each case is a pattern: a value, several values joined by |, or _, which means anything else.

Patterns can also take a value apart: case ("go", direction): fits a pair whose first part is "go", and puts its second part in direction.

for order in ["hi", ("go", "left"), "dance"]:
    match order:
        case "hello" | "hi":
            print("Hello to you!")
        case ("go", direction):
            print("Going", direction)
        case _:
            print("I don't understand")
Output
Hello to you!
Going left
I don't understand

In the game

Turn a list of orders into moves:

for order in ["up", "up", "wave"]:
    match order:
        case "up" | "down" | "left" | "right":
            me.move(order)
        case "wave":
            me.say("Hello!")

Watch out: Put case _: last: it fits everything, so no case after it would ever run.

Part 3

Functions and errors

Breaking a job into named pieces, and handling things going wrong: functions, errors, tests, scope and recursion.

3.1

Functions

Practise it in Code Kingdom 3-1

def gives a few lines a name: a command of your own, to use again and again.

def greet(name): makes a function called greet with one parameter, name. Calling greet("Ada") runs its lines with name set to "Ada".

return sends an answer back to where the function was called, and ends it. A function without return gives back None.

def greet(name):
    print("Hello,", name)

def double(n):
    return n * 2

greet("Ada")
print(double(21))
Output
Hello, Ada
42

In the game

Your own command for chopping, used again and again:

def fill_up():
    tree = me.nearest("tree")
    me.go_to(tree)
    while not me.is_full:
        if me.harvest(tree) == 0:
            break

while True:
    fill_up()
    me.go_to_castle()
    me.deposit()

Watch out: Writing a def doesn't run anything: the function only runs when you call it, with brackets: greet("Ada").

3.2

Errors and exceptions

Practise it in Code Kingdom 3-8

When something goes wrong, Python stops and says what and where. You can also catch it.

An error message tells you the kind of error (NameError, TypeError, ValueError...), the line it happened on, and what went wrong. Read it from the bottom up: the last line says the most.

try: runs some lines, and if one of them fails, except catches the error and runs its own lines instead of stopping. raise makes an error on purpose, when your code finds something it can't go on with.

try:
    number = int("ten")
except ValueError:
    print("That's not a number!")

def take(amount, stock):
    if amount > stock:
        raise ValueError("not enough wood")
    return stock - amount

try:
    take(5, 3)
except ValueError as problem:
    print("Problem:", problem)
Output
That's not a number!
Problem: not enough wood

Watch out: Don't catch every error with a bare except: just to make it go away: name the kind you expect, like except ValueError:.

3.3

Testing and debugging

Practise it in Code Kingdom 3-15

Check that your code does what you think, and hunt bugs down like a detective.

print() is your magnifying glass: print values along the way, and see where they stop being what you expected.

assert checks something that must be true. When it isn't, the program stops with an AssertionError, right where the problem is. Good tests also try the edge cases: zero, one, an empty list, the biggest value.

def biggest(numbers):
    best = numbers[0]
    for n in numbers:
        if n > best:
            best = n
    return best

assert biggest([3, 9, 2]) == 9
assert biggest([5]) == 5
assert biggest([-4, -2]) == -2
print("All tests passed!")
Output
All tests passed!

In the game

Clues in the Output, and a check that stops the script when it fails:

tree = me.nearest("tree")
print("nearest tree:", tree.position, "wood:", tree.amount)
assert tree.amount > 0, "this tree is empty!"

Watch out: A bug is just a surprise you don't understand yet. Change one thing at a time, then run your code again.

3.4

Scope and arguments

Practise it in Code Kingdom 3-21

Names made inside a function stay inside it. Arguments can have defaults and names.

A variable made inside a function is local: it only exists while the function runs, and the rest of the program can't see it. That's why two functions can both use a name like count without mixing them up.

A parameter can have a default: def walk(direction="right", steps=1):. When calling, you can name an argument: walk(steps=3). *numbers collects any number of values into a tuple.

count = 10

def add_one():
    count = 1
    return count

print(add_one(), count)

def walk(direction="right", steps=1):
    return f"{direction} x{steps}"

print(walk(), "|", walk("up"), "|", walk(steps=3))

def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3))
Output
1 10
right x1 | up x1 | right x3
6

In the game

A walk of any length, one step if you don't say:

def walk(direction, steps=1):
    for i in range(steps):
        me.move(direction)

walk("right", 3)
walk("down")

Watch out: To change a variable from outside a function, it needs global name first. Usually it's better to return the new value.

3.5

Recursion

Practise it in Code Kingdom 3-28

A function that calls itself, on a smaller piece of the problem each time.

Recursion solves a big problem by solving a smaller copy of it. Every recursive function needs a base case: a case so simple it's answered straight away, without calling itself again. Without one, it would go on for ever.

It's perfect for things inside things: counting down, folders inside folders, or finding every tile of a lake.

def countdown(n):
    if n == 0:
        print("Lift off!")
        return
    print(n)
    countdown(n - 1)

countdown(3)

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))
Output
3
2
1
Lift off!
120

In the game

A walk that calls itself, one step shorter each time:

def walk(steps):
    if steps == 0:
        me.say("Here!")
        return
    me.move("right")
    walk(steps - 1)

walk(4)

Watch out: Make sure every call gets closer to the base case, or Python stops with a RecursionError.

3.6

Functions as values

Practise it in Code Kingdom 3-35

A function is a value too: you can store it, hand it to another function, or make one in a line.

Without brackets, a function's name is the function itself. You can hand it to another function: sorted(words, key=len) sorts words by their length, because it uses len on every word.

lambda makes a small function in one line: lambda n: n * 2. map() uses a function on every item, and filter() keeps the items it says yes to.

words = ["banana", "fig", "apple"]
print(sorted(words, key=len))
double = lambda n: n * 2
print(double(4))
print(list(map(double, [1, 2, 3])))
print(list(filter(lambda w: "a" in w, words)))
Output
['fig', 'apple', 'banana']
8
[2, 4, 6]
['banana', 'apple']

In the game

The closest tree, and the most hurt unit:

closest = min(game.trees, key=me.distance_to)
weakest = min(game.units, key=lambda u: u.hp)
me.go_to(closest)

Watch out: key=len hands over the function; key=len() would call it straight away, and fail.

Part 4

Objects

Modelling the world as objects: classes, careful designs, families of classes, generators and decorators.

4.1

Classes and objects

Practise it in Code Kingdom 4-1

A class is a blueprint; objects are the things made from it, each with values of its own.

class Knight: starts a blueprint. Its __init__ method runs whenever a new object is made, and self is that object: self.name = name gives it a name of its own.

Functions inside a class are methods: every object made from it can use them, with a dot. The game works this way too: me is a Villager object, and move() is one of its methods.

class Knight:
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp

    def hurt(self, damage):
        self.hp = self.hp - damage
        return self.hp > 0

ada = Knight("Ada", 10)
ben = Knight("Ben", 6)
ada.hurt(3)
print(ada.name, ada.hp, ben.hp)
print(ben.hurt(8))
Output
Ada 7 6
False

In the game

A field of trees as an object, with a method that adds up its wood:

class Field:
    def __init__(self, name, trees):
        self.name = name
        self.trees = trees

    def wood(self):
        return sum(t.amount for t in self.trees)

west = Field("west", [t for t in game.trees if t.x < game.width // 2])
print(west.name, "has", west.wood(), "wood")

Watch out: Every method needs self as its first parameter, and inside it you reach the object's values through self..

4.2

Designing classes

Practise it in Code Kingdom 4-9

Make objects that look after themselves: they print nicely, compare and sort.

Special methods with double underscores let your objects work with Python's own tools: __str__ decides what print() shows, __eq__ what == means, and __lt__ (less than) lets sorted() put them in order.

A property looks like a value but runs a method: @property above def total(self): lets you write crate.total, with no brackets. An object can also be made of other objects: that's called composition.

class Crate:
    def __init__(self, wood, gold):
        self.wood = wood
        self.gold = gold

    @property
    def total(self):
        return self.wood + self.gold

    def __str__(self):
        return f"Crate({self.wood} wood, {self.gold} gold)"

    def __lt__(self, other):
        return self.total < other.total

crates = [Crate(5, 1), Crate(2, 0), Crate(3, 4)]
print(crates[0], crates[0].total)
print([c.total for c in sorted(crates)])
Output
Crate(5 wood, 1 gold) 6
[2, 6, 7]

In the game

A place that prints itself the way you want:

class Spot:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"({self.x}, {self.y})"

home = Spot(game.castle.x, game.castle.y)
print("Home is at", home)

Watch out: Keep each class about one thing. When a class does everything, split it into smaller ones that work together.

4.3

Inheritance

Practise it in Code Kingdom 4-16

A class can be built on another one: it gets everything the parent has, and adds or changes some of it.

class Archer(Unit): makes Archer a child of Unit: an archer can do everything a unit can. When the child writes its own version of a method, that one wins: that's overriding. super() reaches the parent's version, so the child can add to it instead of starting again.

Objects of different classes that have the same methods can be used in the same way: that's polymorphism. isinstance(x, Unit) asks whether x is a Unit, or a child of one.

class Unit:
    def __init__(self, name):
        self.name = name

    def attack(self):
        return f"{self.name} swings a sword"

class Archer(Unit):
    def attack(self):
        return f"{self.name} shoots an arrow"

class Captain(Unit):
    def attack(self):
        return super().attack() + " and shouts orders"

for u in [Unit("Ada"), Archer("Ben"), Captain("Cy")]:
    print(u.attack())
print(isinstance(Archer("Dee"), Unit))
Output
Ada swings a sword
Ben shoots an arrow
Cy swings a sword and shouts orders
True

In the game

In the game, Tree and GoldMine are both children of Resource: that's why both have .amount.

for thing in [me.nearest("tree"), me.nearest("gold")]:
    print(thing.position, thing.amount)

Watch out: Only inherit when the child really is a kind of the parent: an archer is a unit, but a castle isn't a sword.

4.4

Iterators and generators

Practise it in Code Kingdom 4-23

A generator makes its values one at a time, only when they're asked for.

A function with yield instead of return is a generator. Every time a loop asks for the next value, the function runs on to its next yield, hands that value over, and waits there, remembering everything.

So a generator can even go on for ever without filling up the memory. next() asks for one value by hand.

def countdown(n):
    while n > 0:
        yield n
        n = n - 1

for x in countdown(3):
    print(x)

evens = (n for n in range(100) if n % 2 == 0)
print(next(evens), next(evens), next(evens))
Output
3
2
1
0 2 4

In the game

In the game, a generator can plan the steps, while the loop that uses it takes them:

def square(size):
    for direction in ["right", "down", "left", "up"]:
        for i in range(size):
            yield direction

for step in square(3):
    me.move(step)

Watch out: A generator can only be gone through once. To start again, call the function again.

4.5

Decorators and with

Practise it in Code Kingdom 4-29

A decorator wraps a function to add something to it; with makes sure a job is finished properly.

A decorator is a function that takes a function and gives back a new one that does a little more: counts its calls, shows what happens, or remembers answers. @shout on the line above a def wraps that function in shout.

with starts something and makes sure it's finished, even when an error happens in between. Any object with the methods __enter__ and __exit__ works with with.

def shout(func):
    def wrapper(name):
        return func(name).upper() + "!"
    return wrapper

@shout
def greet(name):
    return "hello " + name

print(greet("ada"))

class Timer:
    def __enter__(self):
        print("start")
        return self

    def __exit__(self, *problem):
        print("stop")

with Timer():
    print("working...")
Output
HELLO ADA!
start
working...
stop

Watch out: The wrapper has to call the function it wraps and return its answer, or the wrapped function stops working.

Part 5

Programs and systems

Many scripts at once, talking through messages: searching, sorting, graphs, modules and the final project.

5.1

Searching and sorting

Practise it in Code Kingdom 5-1

Find things quickly and put them in order: two jobs nearly every program does.

Linear search looks at every item, one by one, until it finds the one it wants. When the list is sorted, binary search is much faster: look in the middle, throw away the half the answer can't be in, and do it again.

Python sorts for you with sorted() and .sort(), but writing a sort yourself shows how it works: bubble sort swaps neighbours that are the wrong way round, again and again, until nothing moves.

def binary_search(items, target):
    low, high = 0, len(items) - 1
    while low <= high:
        middle = (low + high) // 2
        if items[middle] == target:
            return middle
        if items[middle] < target:
            low = middle + 1
        else:
            high = middle - 1
    return None

numbers = [2, 5, 8, 12, 16, 23, 38]
print(binary_search(numbers, 23))
print(binary_search(numbers, 7))
Output
5
None

In the game

The three closest trees, closest first:

trees = sorted(game.trees, key=me.distance_to)
for tree in trees[:3]:
    print(tree.position, me.distance_to(tree))

Watch out: Binary search only works on a list that's already sorted.

5.2

Messages and events

Practise it in Code Kingdom 5-4

Programs that talk: one part sends a message, and another reacts when it arrives.

Big programs are made of parts that work at the same time. Instead of reaching into each other, they send messages: a name and some data. Each part keeps what it receives in an inbox, and reacts to each event in turn.

A part can also be in a state, like working, hiding or resting, and messages can change it. That's called a state machine.

inbox = []

def send(name, data=None):
    inbox.append((name, data))

state = "working"
send("raid", (12, 4))
send("all clear")
for name, data in inbox:
    if name == "raid":
        state = "hiding"
    elif name == "all clear":
        state = "working"
    print(name, data, "->", state)
Output
raid (12, 4) -> hiding
all clear None -> working

In the game

The commander raises the alarm, and the villagers run home:

# commander.py
if len(game.enemies) > 0:
    game.broadcast("raid", data=game.enemies[0].position)

# villager.py
msg = me.inbox.next()
if msg is not None and msg.name == "raid":
    me.go_to_castle()

Watch out: Messages arrive a step later, in the order they were sent. Never wait for an answer nobody is going to send.

5.3

Graphs and paths

Practise it in Code Kingdom 5-12

A graph is places joined by paths. Searching it finds the way from here to there.

The island is a graph: every tile is a place, joined to the tiles around it. Breadth-first search explores in rings, nearest first, using a queue, so the first time it reaches the goal, it has found a shortest way. Depth-first search follows one path as far as it goes before trying another.

Keep a set of the places you've already seen, or you'll go round in circles for ever.

paths = {
    "beach": ["forest", "hill"],
    "forest": ["beach", "cave"],
    "hill": ["beach", "castle"],
    "cave": ["forest", "castle"],
    "castle": ["hill", "cave"],
    "lake": [],
}

def steps(start, goal):
    queue = [(start, 0)]
    seen = {start}
    while queue:
        place, n = queue.pop(0)
        if place == goal:
            return n
        for next_place in paths[place]:
            if next_place not in seen:
                seen.add(next_place)
                queue.append((next_place, n + 1))
    return None

print(steps("beach", "castle"))
print(steps("beach", "lake"))
Output
2
None

Watch out: Add a place to the seen set when you put it in the queue, not when you take it out, or the same place gets queued many times.

5.4

Clean code

Practise it in Code Kingdom 5-17

Code is read more often than it's written: make it easy to read, for others and for future you.

Good names say what a value is: trees_left, not t. A value that never changes gets a name in capitals at the top: that's a constant, like HOUSE_COST = 30. Short functions that each do one job are easier to test and to fix.

Type hints say what a function takes and gives back: def cost(houses: int) -> int:. Python doesn't check them, but they help whoever reads the code. Tidying code without changing what it does is called refactoring.

HOUSE_COST = 30

def houses_we_can_build(wood: int) -> int:
    return wood // HOUSE_COST

def report(wood: int) -> str:
    houses = houses_we_can_build(wood)
    return f"{wood} wood is enough for {houses} houses"

print(report(95))
Output
95 wood is enough for 3 houses

Watch out: Tidy one thing at a time, and run your code after every change, so you know it still works.

5.5

Modules

Practise it in Code Kingdom 5-24

A module is a box of ready-made tools, and import opens it.

Python comes with lots of modules. import math gives you math.sqrt(), math.pi, math.floor() and more, used with the module's name and a dot. from math import sqrt brings in just one tool, so you can write sqrt(16), and import math as m gives the module a shorter name.

To see what a module has, read its documentation, or ask Python: help(math).

import math
from math import sqrt
import math as m

print(math.sqrt(16), sqrt(2) > 1.4)
print(math.floor(3.7), math.ceil(3.2))
print(round(m.pi, 2))
Output
4.0 True
3 4
3.14

In the game

How far is the castle, as the crow flies?

import math

dx = game.castle.x - me.x
dy = game.castle.y - me.y
print("As the crow flies:", round(math.hypot(dx, dy), 1))

Watch out: Don't name a variable after a tool you've imported: sqrt = 5 hides the sqrt function. In the game, math is the one module you can import.