Learning Goals
3 minBy the end of this lesson you can:
- Define a function with
def, a colon and an indented body. - Call that function by name, as many times as you want.
- Explain why repeated code is a problem, not just untidy.
- Spot the three mistakes that stop a function running at all.
Warm-Up · Count the Copies
5 minMia wrote a receipt printer for her mother's shop runcit. Read it, and answer the two questions underneath.
print("=========================") print(" SHOP RUNCIT MIA ") print("=========================") print("Pancake $1.50") print("=========================") print(" SHOP RUNCIT MIA ") print("=========================") print("Hot chocolate $2.00") print("=========================") print(" SHOP RUNCIT MIA ") print("=========================") print("Pizza $4.50")
- The shop changes its name to Shop Runcit Mia & Sons. How many lines must you edit?
- If there were forty receipts instead of three, how many would you edit — and how many would you get wrong?
It is three chances to make a mistake instead of one. Every copy is a place the next change can be forgotten. That is the real argument for functions, and it is why programmers say DRY — don't repeat yourself.
New Concept · Defining and Calling
12 minA function has two halves, and they happen at different moments.
1 · Definition — you describe the job and give it a name. Nothing runs yet.
def print_header(): print("=========================") print(" SHOP RUNCIT MIA ") print("=========================")
Four things to notice, and all four are compulsory:
def— the keyword that starts a definition.print_header— the name. Same rules as a variable: lower case, underscores, no spaces, and a verb reads best.()— empty brackets for now. Lesson 2 fills them.:then an indented block. The indented lines are the function; the first line back at the margin is not.
2 · The call — you say the name, and now the body runs.
print_header() print("Pancake $1.50") print_header() print("Hot chocolate $2.00")
The brackets are what make it a call. print_header on its own is just the name of the function — Python will happily accept it and do nothing at all.
Python reads your file top to bottom. If the call comes before the def, the name does not exist yet and you get NameError. Put your functions at the top of the file and the code that uses them underneath — that is the normal shape of a Python program.
One more habit worth starting today. A string on the first line of the body is a docstring: a note explaining the job, which stays with the function forever.
def print_header(): """Print the three-line shop header.""" print("=========================") print(" SHOP RUNCIT MIA ") print("=========================")
Worked Example · The Receipt, Rewritten
12 minType this out and run it. It does exactly what Mia's script did.
def print_header(): """Print the three-line shop header.""" print("=========================") print(" SHOP RUNCIT MIA ") print("=========================") def print_thanks(): """Print the closing message.""" print("-------------------------") print(" Thank you! Come again") print() print_header() print("Pancake $1.50") print_thanks() print_header() print("Hot chocolate $2.00") print_thanks()
Output
========================= SHOP RUNCIT MIA ========================= Pancake $1.50 ------------------------- Thank you! Come again ========================= SHOP RUNCIT MIA ========================= Hot chocolate $2.00 ------------------------- Thank you! Come again
Now do the thing that proves the point. Change the shop name to Shop Runcit Mia & Sons. One line. Run it again and every receipt has changed.
Python meets def print_header and remembers it. It meets def print_thanks and remembers that too. Nothing has been printed yet. Only at print_header() — line 17 — does anything appear on screen. Definitions are instructions to remember; calls are instructions to do.
Try It Yourself
13 minWrite a function called print_line that prints thirty dashes. Call it three times, with a different message printed between each call.
Hint
def print_line(): """Print a divider.""" print("-" * 30) print_line() print("Menu") print_line()
"-" * 30 beats typing thirty dashes, and it is easy to change to forty.
Write three functions — show_title, show_menu, show_footer — for a canteen ordering program. Then call them in order, so the whole screen is drawn by three lines at the bottom of your file.
Then rearrange those three calls to print the footer first. Notice that you changed the order of the program without touching any of the printing.
Mini-Challenge 🔥 · Debug: Three Ways to Break a Function
8 minLeo's program prints the item but no header, and then crashes. There are three separate mistakes. Find them all before you look.
show_welcome()
def show_welcome()
print("Welcome to the canteen!")
print("Today: pizza")
show_welcomeAnswer
- Called before defined. The first line runs before Python has read the
def, so it raisesNameError: name 'show_welcome' is not defined. Move the definition to the top. - No colon.
def show_welcome()must end in:, or Python stops with aSyntaxError. - No brackets on the last line.
show_welcomeis the name of the function, not a call. Python evaluates it, shrugs, and does nothing. It must beshow_welcome().
There is a fourth, quieter problem: print("Today: pizza") sits at the left margin, so it is not part of the function even though it looks close to it. Indentation is the only thing that decides what is inside a function.
Recap
3 mindef name(): plus an indented block defines a function; name() with brackets calls it. Definitions only remember, calls do, and the definition must come first in the file. Everything indented under the def is inside; the first line back at the margin is outside. Write the job once, and every future change is one edit instead of forty.
Vocabulary Card
- function
- A named block of code you can run whenever you like by calling its name.
- def
- The keyword that begins a definition. Ends with
()and a colon. - call
- Running a function by writing its name followed by brackets:
print_header(). - docstring
- A string on the first line of the body that says what the function is for.
- DRY
- "Don't repeat yourself" — say something once so there is only one place to change it.
Homework
4 minFind a program you have already written that repeats itself — a menu, a game screen, a header printed more than once. Rewrite it so the repeated part is a function, called from the places that used to hold the copies.
Hand in both versions, and one sentence: how many lines would you edit to change the repeated part, before and after?
Hint: if you have nothing repetitive to hand, write a program that prints a Kad Ucapan (greeting card) three times — border, message, border — using two functions.
Sample · kad_ucapan.py
# kad_ucapan.py - the same card, three times, one place to edit def print_border(): """Print the decorative border used above and below the message.""" print("*" * 34) def print_card(message): """Print one greeting card. (message comes in lesson 2 - peek ahead!)""" print_border() print("*" + message.center(32) + "*") print_border() print() print_card("Happy Birthday!") print_card("Happy Symmetry!") print_card("Gong Xi Fa Cai!")
Before: 9 lines to change the border. After: 1. If you wrote three separate functions instead of one that takes a message, that is a perfectly good answer for today — lesson 2 is exactly about collapsing those three into one.