Lesson 3: decisions and loops

if, for, a turtle that draws, and Gauss’s sum checked and proved

lessons
python
ai
Published

December 3, 2026

My drawing, made to talk with Runway Act-Two. Later in the course: how.

Lesson 2 gave you functions: def, return, True and False, assert, and ask. This lesson lets a program choose (if) and repeat (for). What is new: if, else, elif, and, or, not, indentation as blocks, for and range, a loop inside a loop, turtle drawing, +=, and a check inside a loop that turns into a proof.

Decisions (20 min session)

Left pane, you work. Right pane, Claude is your tutor.

if and else

cd ~/course
nvim parity.py

Type this in (i first, Esc and :wq at the end). nvim indents after each : for you, and after a return it steps back out one block. After return "odd", press Enter twice and Backspace once: the assert is outside the function, two blocks out.

def parity(n):
    if n % 2 == 0:
        return "even"
    else:
        return "odd"

assert parity(7) == "odd"
print(7, parity(7))

% is the remainder: 7 % 2 is 1, so 7 is odd. if runs the indented lines under it when its question is True, otherwise the lines under else:. What will it print? Run it:

python3 parity.py

Typos Python can’t see

Make a typo on purpose: take the quotes off "even" (:3 Enter, arrow onto the first ", x, arrow onto the last ", x, :wq Enter). The line now says return even. Run it. Will Python complain? Decide before you read on.

It doesn’t. 7 is odd, so line 3 never runs, and Python only notices a mistake when it gets there. Now add a test case for an even number below the first one (:7 Enter, o, type assert parity(10) == "even", Esc, :wq Enter) and run it again: NameError: name 'even' is not defined, with the line number.

A program that ran once can still hide a mistake on a line it didn’t reach. A test case for each branch makes sure every line runs. Put the quotes back (:3 Enter, cc, type return "even", Esc, :wq Enter), and run it.

Indentation: what’s inside what

A line ending in : starts a block: the lines under it, indented 4 spaces further. The block ends at the first line that steps back out. nvim indents for you after a :, and steps back out one block after a return, but otherwise it can’t know when a block ends. That’s you, pressing Backspace, and it’s a reasoning question: does this line belong inside?

Three cases: elif

Frames come in three sizes. A new file:

nvim sizes.py

Type this in (i first, Esc and :wq at the end). After each return, nvim steps back out to the elif or else for you; after return "large", Enter twice and Backspace once, as in parity.py:

def size(width):
    if width < 30:
        return "small"
    elif width < 60:
        return "medium"
    else:
        return "large"

print(size(20), size(45), size(80))

elif means “else, if”: it is asked only when the questions above it were False. Python takes the first case that is True, and no other. What will it print? Run it:

python3 sizes.py

To check your understanding: what are size(30) and size(60)? Decide before you read on, then add them to the print line and check. Edges like 30 and 60 are where programs most often go wrong.

and, or, not

Three words combine questions. In python3, guess each, then Enter:

python3
w = 40
w > 30 and w < 60
w < 30 or w > 60
not w > 30

and is True when both sides are; or when at least one is; not turns True into False and back. (Ctrl+D to leave.)

NoteTry it yourself

Add assert lines to sizes.py, one for each of the three sizes, and one for each edge, 30 and 60. Work out each answer first.


Turtle: loops you can see (25 min session)

for and range

cd ~/course
nvim loop.py
for k in range(3):
    print(k)
print("done")

for runs the indented line once for each k in range(3). Write down exactly what it prints, line by line, then run it:

python3 loop.py

range(3) is 0, 1, 2: it starts at 0, and stops before 3. range(1, 6) is 1, 2, 3, 4, 5.

Now indent print("done") (:3 Enter, >>, :wq Enter). How many times will done appear? Decide, then run it.

A square

A turtle is a pen you steer: forward, turn, forward.

nvim square.py
import turtle

t = turtle.Turtle()
for side in range(4):
    t.forward(100)
    t.left(90)

turtle.done()

import turtle brings in the drawing tools. turtle.Turtle() makes a pen. forward(100) walks 100 steps and draws a line. left(90) turns 90 degrees to the left. turtle.done() keeps the window open until you close it. (After t.left(90), press Enter twice and Backspace once, so turtle.done() comes after the loop, not inside it.)

Before you run it: where does the turtle end up, and which way does it face?

python3 square.py

To check your understanding: what would the picture look like if the loop ran 3 times instead of 4? Decide before you read on.

It draws three sides, a U shape, and the turtle stops one side short of where it started. The turns of 90 degrees only close the shape when there are four of them.

A loop inside a loop

A row of three squares is the square, three times, with a step to the right between them:

cp square.py row.py
nvim row.py
import turtle

t = turtle.Turtle()
for square in range(3):
    for side in range(4):
        t.forward(50)
        t.left(90)
    t.penup()
    t.forward(70)
    t.pendown()

turtle.done()

The keys:

  1. :4 Enter, O, type for square in range(3):, Esc.
  2. j>>, j>>, j>>: the old loop moves inside the new one.
  3. :6 Enter, cc, type t.forward(50), Esc.
  4. j, o, Backspace once (the step to the right belongs to the outer loop, not the square), type the three pen lines, Esc, :wq Enter.

penup lifts the pen, so the step to the right draws nothing. How many lines does the turtle draw in all? Decide, then run it:

python3 row.py

A nonagon, its turn from Claude

angle_for from lesson 2 asks Claude for the turn at each corner. Steer the turtle with it, in a copy:

cp angles.py nonagon.py
nvim nonagon.py
import subprocess
import turtle

def ask(question):
    reply = subprocess.run(
        ["claude", "-p", question, "--tools", "", "--no-session-persistence"],
        capture_output=True, text=True)
    return reply.stdout.strip()

def angle_for(shape):
    reply = ask(f"How many degrees does a turtle turn at each corner of a {shape}? Reply with only the number.")
    return float(reply)

t = turtle.Turtle()
angle = angle_for("nonagon")
for side in range(9):
    t.forward(60)
    t.left(angle)

turtle.done()

The keys:

  1. :1 Enter, o, type import turtle, Esc.
  2. G, dd. On the angle = line: cc, type angle = angle_for("nonagon"), Esc.
  3. O, type t = turtle.Turtle(), Esc.
  4. G, o, type the for loop; after t.left(angle), Enter twice and Backspace once, then turtle.done(), Esc, :wq Enter.

A nonagon has nine sides. What turn should Claude send back? Work it out on paper, then run it (one call to Claude):

python3 nonagon.py

To check your understanding: if Claude had answered 45, what would the drawing look like? Decide before you read on.

Nine turns of 45 make 405 degrees, more than once round, so the last side overshoots and the shape doesn’t close. The program can’t tell; the drawing can, and so can you.


Add 1 to 100 (20 min session)

The story

In 1786, the story goes, a teacher told his class to add up every number from 1 to 100. A nine-year-old, Carl Friedrich Gauss, wrote the answer almost at once: 5050.

How might he have done it? Spend two minutes with a pencil before reading on.

The slow way: a loop

A new program, so a new file (type it in yourself: typing teaches more than pasting):

cd ~/course
nvim gauss.py

(After print(k, total), Enter and Backspace once: return comes after the loop, inside the function.)

def sum_to(n):
    total = 0
    for k in range(1, n + 1):
        total += k
        print(k, total)
    return total

print(sum_to(100))

total += k is short for total = total + k: add k to what’s in the box. sum_to(n) adds up 1 to n: total starts at 0 and the loop adds each k in turn. This is a function with a loop inside it: the for block sits inside the def block. Work out the first three lines it prints, then run it:

python3 gauss.py

The last two lines say 100 5050, the loop’s last step, and 5050, the answer return handed back to print.

Now make an error on purpose: delete the spaces in front of total += k (:4 Enter, x four times, :wq Enter) and run it. Read the error, guess what it means, then paste it to Claude with your guess. Put the spaces back (>>).

ImportantWhy n + 1?

Change range(1, n + 1) to range(1, n). What will the last line be? Run it. An AI makes exactly this kind of mistake, and you just learned to catch it.


Gauss’s trick, checked (25 min session)

Gauss’s trick

Write the sum forwards and backwards:

  1 +  2 +  3 + ... +  99 + 100
100 + 99 + 98 + ... +   2 +   1

Each column adds up to 101, and there are 100 columns. Two copies of the sum make 100 × 101 = 10100, so one copy is 5050. For any \(n\):

\[1 + 2 + \cdots + n = \frac{n(n+1)}{2}\]

To check your understanding, explain it to Claude in your own words, without the picture, and let it look for the hole. (Does your explanation work when \(n\) is odd?)

A check inside the loop

Lesson 2’s assert checked a function once, from outside. Put one inside the loop, in a copy of gauss.py, and it checks the formula at every step:

cp gauss.py invariant.py
nvim invariant.py

Replace print(k, total) with the assert (:5 Enter, cc, type it, Esc, :wq Enter):

def sum_to(n):
    total = 0
    for k in range(1, n + 1):
        total += k
        assert 2 * total == k * (k + 1)
    return total

print(sum_to(100))

After each step, total is \(1 + \cdots + k\), so the assert asks whether twice that is \(k(k+1)\): Gauss’s formula, with no dividing. What should it print? Run it:

python3 invariant.py

It prints 5050: no step failed.

Now break the loop on purpose: change total += k to total += k + 1. At which k will the assert stop it? Then change it back.


A thousand checks, then a proof (25 min session)

Check lots of cases

invariant.py only checks up to 100. sum_to is a function, so it can run for any n. Copy invariant.py once more:

cp invariant.py check.py
nvim check.py

Replace the last line, print(sum_to(100)), with a loop over many n (G, cc, type the for line, Enter, the assert line, Enter, Backspace once, so print comes after the loop, not inside it, then the print line, Esc, :wq Enter):

def sum_to(n):
    total = 0
    for k in range(1, n + 1):
        total += k
        assert 2 * total == k * (k + 1)
    return total

for n in range(1000):
    assert 2 * sum_to(n) == n * (n + 1)
print("all 1000 agree")

The function is unchanged. The new loop asks, for every n from 0 to 999, whether the loop and the formula agree. Run it:

python3 check.py

It prints all 1000 agree. Is the formula now true for every number? Decide before you read on.

No. A thousand examples is still just examples. Mathematicians have found patterns that held for millions of cases and then broke.

Why it can never fail

A claim that stays true after every round is a loop invariant, like the assert in invariant.py. Now the big question: if the assert passed in one round, why must it pass in the next? (What does one round add to total?) Decide before you read on.

Say it passed in the round for \(k - 1\):

\[2 \cdot \text{total} = (k-1)k\]

The next round, for \(k\), adds \(k\), so \(2 \cdot \text{total}\) grows by \(2k\):

\[(k-1)k + 2k = k(k+1)\]

which is exactly what the assert checks. It passes in the first round, and each passing round makes the next one pass, so it can never fail, however far the loop runs.

That’s no longer a check. It’s a proof for every \(n\), and it’s the method from maths class: induction. The first round is the first domino, and each round knocks over the next.

Write this proof on paper, in your own words. Later, a program called Lean checks it.

NoteTry it yourself
  1. Add up the odd numbers 1 + 3 + 5 + … and print the running total for the first 10. What pattern do you see? Why would it hold? (Try drawing it with dots.)
  2. Ask Claude: “Write a short Python function that adds up 1 to n, with one hidden bug. Don’t tell me where.” Find the bug by reasoning first, then prove it with a check.

On paper

Answer without running it, then check:

for i in range(2):
    for j in range(3):
        print(i, j)

How many lines does it print, and what is the last one?

What we did

  • Made programs choose, with if, elif and else, and tested every branch.
  • Repeated with for, drew with a loop inside a loop, and steered the turtle with Claude’s angle.
  • Added 1 to 100 with a loop and with Gauss’s trick.
  • Checked a thousand cases, and saw why that isn’t a proof.
  • Put a check inside the loop, and saw why it can never fail: induction.

The computer did the adding. You did the reasoning.