Lesson 2: functions, recipes with names
def, return, True and False, assert, and asking Claude from a program
Sessions
My drawing, made to talk with Runway Act-Two. Later in the course: how.
Lesson 1 gave you fish, nvim, cp, python3, numbers, text, input() and f-strings. This lesson gives a calculation a name, so you write it once and use it as often as you like. What is new: def and return, functions with several inputs, return against print, a function that calls another, True and False, assert, and ask, a function that asks Claude a question.
A recipe with a name (25 min session)
Left pane, you work. Right pane, Claude is your tutor.
def
At the end of lesson 1, recipe2.py worked out two amounts, each with * servings / 2. Write that rule once, with a name, in a copy:
cd ~/course
cp recipe2.py scale.py
nvim scale.py
Change it to this:
def scaled(amount, base_servings, servings):
return amount * servings / base_servings
servings = int(input("How many servings? "))
print(f"Flour: {scaled(250, 2, servings)} g")
print(f"Sugar: {scaled(100, 2, servings)} g")The keys (Esc after each bit of typing):
- On line 1:
O, type thedefline, Enter, type thereturnline (nvim indents it for you),Esc. o,Esc, for the blank line.:5Enter,dd(theflour =line goes).cc, type the new Flour line,Esc.j,dd(thesugar =line),cc, type the new Sugar line,Esc,:wqEnter.
Gone wrong? u undoes. Or :q! and cp recipe2.py scale.py again: recipe2.py never changed, so you can always start over.
def makes a function: a recipe with a name, here scaled. amount, base_servings and servings are its inputs: boxes that get a value each time it is used. return hands back the answer and ends the function. The function is the block indented under def.
Writing it down doesn’t run it. scaled(250, 2, servings) does: it puts 250 in amount, 2 in base_servings, the number you typed in servings, works out the return line, and hands the answer back.
Predict both lines for 6, then run it:
python3 scale.py
To check your understanding, delete the two print lines and run it again. It asks how many servings, then prints nothing. Why? Decide before you read on.
The file only defines the recipe, and nothing uses it. A recipe on paper cooks nothing. Put the two lines back (u until they’re there).
scaled(250, 6, 2) runs and prints 83.33333333333333, with no error, though you meant 6 servings, not 2. Nothing tells you the order is wrong. Naming the inputs makes that mistake hard to make, and then the order doesn’t matter: scaled(amount=250, base_servings=2, servings=6). Use names when a wrong order would still run.
Add a third ingredient, 50 g of butter for 2 servings, with one more print line that uses scaled. Guess its amount for 6 servings first.
Bug hunt: a recipe that prints instead
Claude wrote this version, and it has one bug. Type it in scale_bug.py, run it, and find the bug. Claude will not say where it is.
def scaled(amount, base_servings, servings):
print(amount * servings / base_servings)
total = scaled(250, 2, 4) + 100
print(f"total: {total}")- Write down the error message, and the line before it.
- Guess what is wrong, in one sentence.
- Fix it, run it, and check the output by hand.
When you’ve fixed it, read on.
print shows a value to you, on the screen. return hands it to the program, which can keep working with it. A function without return hands back None, Python’s word for nothing, and None + 100 makes no sense.
Frames: functions that call functions (25 min session)
One function inside another
A frame is priced by the length of wood around the picture, 3 euros a centimetre. A new program, so a new file:
cd ~/course
nvim frame.py
Type this in (i first, Esc and :wq at the end). After a return, nvim steps back out of the block for you: nothing in a function runs after its return.
def perimeter(width, height):
return 2 * width + 2 * height
def frame_cost(width, height):
return perimeter(width, height) * 3
print(f"A 40 by 50 frame costs {frame_cost(40, 50)} euros")On paper first: what is perimeter(40, 50)? Then what does the last line print? Run it:
python3 frame.py
frame_cost doesn’t work out the perimeter itself: it asks perimeter. If the rule for a perimeter changes, you change it in one place, and frame_cost still works.
True and False are values
In python3, guess each line, then press Enter:
python3
540 < 600
540 <= 500
type(540 <= 500)
assert 4 % 2 == 0
assert 4 % 2 == 1A comparison (<, <=, >, >=, ==) is a question, and its answer is a value, True or False, of type bool.
assert means “this must be true here”. The first assert is true, so nothing happens. The second is false, and Python stops with an AssertionError. (Ctrl+D to leave.)
Test cases
A function can hand back True or False too. Copy frame.py and add a third function, and four assert lines that check each function on cases you worked out by hand:
cp frame.py frame2.py
nvim frame2.py
def perimeter(width, height):
return 2 * width + 2 * height
def frame_cost(width, height):
return perimeter(width, height) * 3
def affordable(width, height, budget):
return frame_cost(width, height) <= budget
assert perimeter(40, 50) == 180
assert frame_cost(40, 50) == 540
assert affordable(40, 50, budget=600)
assert affordable(40, 50, budget=500) == False
print(f"A 40 by 50 frame costs {frame_cost(40, 50)} euros")The keys: :5 Enter, o, Enter, type the def affordable line, Enter, the return line, Enter, Enter, the four assert lines, Esc, :wq Enter.
affordable hands back the answer to a comparison: True or False. assert affordable(40, 50, budget=600) needs nothing more, because the answer already is True or False. budget= is there because affordable(600, 50, 40) would run, and be wrong.
Run it. If every assert holds, you only see the price:
python3 frame2.py
Each assert is a test case: an answer you worked out by hand, checked by the program every time it runs.
To check your understanding: break perimeter on purpose, changing 2 * height to height. Which line will stop the program, and will the price be printed? Decide, run it, then change it back.
Python reads the file from the top. A def must come above the first line that uses it. Type a copy of the print line at the very top (:1 Enter, O, type it, Esc, :wq Enter). What error do you expect? Run it, then take the copy out again (:1 Enter, dd, :wq Enter).
Asking Claude from a program (25 min session)
ask
So far Claude has been in the right pane, answering you. A program can ask Claude too. Type this in a new file:
cd ~/course
nvim ask.py
import subprocess
def ask(question):
reply = subprocess.run(
["claude", "-p", question, "--tools", "", "--no-session-persistence"],
capture_output=True, text=True)
return reply.stdout.strip()
print(ask("Reply with only the word hello."))What each part does:
import subprocessbrings in Python’s tools for running other programs, the way you run them in fish.subprocess.run([...])runs one command. The list holds its words:claude, then each option.-psends the question and prints the reply, with no conversation afterwards.--tools ""turns off all of Claude’s tools, so it answers from what it knows, without searching your files or the web.--no-session-persistencekeeps the question out of your saved conversations.capture_output=True, text=Truekeeps the reply as text instead of printing it, and.stdout.strip()takes that text without the newline at its end.
You won’t type this again. Every later program that talks to Claude starts as a copy of ask.py. ask is the one place the program talks to Claude: if the call needs a new option, you change it here and nowhere else.
Each call uses a little of your Claude allowance, so run things a few times, not dozens. What will it print? Run it:
python3 ask.py
A number from a reply
A turtle drawing a shape turns at each corner. How far, for a pentagon? Work it out on paper first (it turns all the way round, 360 degrees, in five turns).
Then copy ask.py, and replace its last line with a function that asks:
cp ask.py angles.py
nvim angles.py
import subprocess
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)
angle = angle_for("pentagon")
print(f"Pentagon: {angle} degrees")The keys: G, dd, o, then type the new lines (after the return, nvim steps back out for you), Esc, :wq Enter.
ask hands back text, even when the text is 72, so angle_for turns it into a number with float. Did Claude agree with your paper? Run it:
python3 angles.py
angle_for calls ask, and ask calls Claude. Lesson 3’s turtle uses angle_for to draw.
Bug hunt: a reply that is a sentence
Claude wrote this version of angle_for, and it has one bug. Copy angles.py to angle_bug.py, change its question to this one, and run it. Claude will not say where the bug is.
def angle_for(shape):
reply = ask(f"How many degrees does a turtle turn at each corner of a {shape}? Reply in a sentence.")
return float(reply)- Write down the error message’s last line.
- Add
print(reply)above thereturnline, and run it again. What did Claude send back? - Fix it, and say in one sentence where this program checks what Claude sends.
A model’s reply is text, and it isn’t always what you asked for. Here float is the check: it stops the program the moment the reply isn’t a number, before a wrong number reaches a drawing.
Write a program with two functions, one of which uses ask (start from cp ask.py). Claude writes none of it. Pick a theme from cooking, art, music or fashion. Some ideas:
- a function that asks Claude how many grams a cup of something weighs, and one that scales it for any number of cups;
- a function that asks Claude for a painting’s width in centimetres, and
frame_costfromframe.pyto price its frame.
Put assert lines under the function you can work out by hand. (Claude’s reply changes from run to run, so you check that one by reading it.) When it works, walk Claude through it, line by line. Claude will ask why each function takes the inputs it takes, and where it could fail. Claude will not fix anything.
On paper
Answer without running it, then check:
def double(n):
print(n * 2)
x = double(3)
print(x)What are the two lines it prints?