Learning Goals
3 minBy the end of this lesson you can:
- Write a function with
def name():, indent its body, and explain why the indentation matters. - Call a function by writing its name followed by
()— and explain whygreeton its own does nothing. - Call the same function many times to see it run repeatedly without copy-pasting code.
Warm-Up
5 minLook at this script. The same three lines repeat over and over:
print("=" * 30) print("Welcome to the Hub!") print("=" * 30) # ... user does some stuff ... print("=" * 30) print("Welcome to the Hub!") print("=" * 30) # ... user does more stuff ... print("=" * 30) print("Welcome to the Hub!") print("=" * 30)
What's wrong with this code? Three things really:
- It's long for what it actually does.
- If we ever change the banner text — say, "Welcome to Advaslearning Hub!" — we have to fix it in three places. Miss one and the program looks inconsistent.
- The idea "print the banner" is hidden inside three identical-looking blobs. You can't read the program at a glance.
The fix is to invent a name for "those three lines" — call it print_banner — and reuse the name. That's a function.
Three reasons. Less repetition. One place to change things. And — most importantly — your main program reads like a story instead of a wall of details.
New Concept · def, Call, Repeat
14 minThe recipe analogy
A function is a written recipe. You write the recipe once, on a card. You follow the recipe (cook it) whenever you're hungry. Writing the recipe is not the same as eating dinner; you have to actually fetch the card and follow the steps.
In Python, the same idea has two parts:
- Defining the function — writing the recipe. Uses the keyword
def. - Calling the function — actually running it. You call it by writing the name followed by
().
The shape of a function
def print_banner(): print("=" * 30) print("Welcome to the Hub!") print("=" * 30)
Read it piece by piece:
def— the keyword that says "I'm defining a function".print_banner— the function's name. Same rules as variable names from PY-L1-03: lowercase, words joined by underscores, no spaces.()— the parentheses are required, even when the function takes no inputs. They're what makesprint_bannera function and not just a variable.:— the colon, same asifandfor— opens the body.- Everything indented underneath is the function's body. Indentation is how Python tells the body apart from the rest of the file.
Defining ≠ running
If you only write the def block and run the file, nothing prints. The recipe is on the card, but no one's cooking. To actually run the function, call it:
def print_banner(): print("=" * 30) print("Welcome to the Hub!") print("=" * 30) print_banner() # ← THIS is what makes it actually print.
Call the same recipe many times
The whole point. Once defined, call it as many times as you want:
def print_banner(): print("=" * 30) print("Welcome to the Hub!") print("=" * 30) print_banner() print("First class starts now.") print_banner() print("Break time.") print_banner()
============================== Welcome to the Hub! ============================== First class starts now. ============================== Welcome to the Hub! ============================== Break time. ============================== Welcome to the Hub! ==============================
Three calls, twelve lines of output, and the function's body is written exactly once. If you want to change the banner text, you change it in one place and every call updates.
Forgetting the () — the silent bug
def print_banner(): print("=" * 30) print("Welcome to the Hub!") print("=" * 30) print_banner # ← oops, missing the ()
Run that and you'll see… nothing useful. The line print_banner on its own just looks up the function, gets a reference to it, and throws it away. No call, no banner. Always include the () when you actually want the function to run.
def writes the recipe. () cooks the recipe. You always need both, in that order, somewhere in your file.
Worked Example · Café Greeter
12 minYou're writing the welcome screen for a small mamak ordering app. Every time a new customer walks in, three things happen: the screen clears with a banner, a greeting prints, and the menu of the day is shown. Today the function takes no inputs — it just prints the same intro every time.
Step 1 · Write the function
def welcome_customer(): print("=" * 35) print("Selamat datang to Mamak Express!") print("=" * 35) print("Tonight's menu: roti canai, nasi lemak, teh tarik.") print() # blank line for breathing room
Five lines of body. The empty print() at the end is a tiny trick — it prints just a newline so the next thing on the terminal has space.
Step 2 · Call it
welcome_customer()
That single line runs the whole five-line body. Try it.
Step 3 · Use it in a tiny program
Save as cafe.py:
Code
# cafe.py — Mamak Express welcome screen def welcome_customer(): print("=" * 35) print("Selamat datang to Mamak Express!") print("=" * 35) print("Tonight's menu: roti canai, nasi lemak, teh tarik.") print() # main program starts here welcome_customer() order1 = input("Customer 1 — what would you like? ") print("Got it:", order1) welcome_customer() order2 = input("Customer 2 — what would you like? ") print("Got it:", order2)
Sample run
=================================== Selamat datang to Mamak Express! =================================== Tonight's menu: roti canai, nasi lemak, teh tarik. Customer 1 — what would you like? roti canai Got it: roti canai =================================== Selamat datang to Mamak Express! =================================== Tonight's menu: roti canai, nasi lemak, teh tarik. Customer 2 — what would you like? nasi lemak Got it: nasi lemak
Notice how the main program at the bottom is now short and readable: welcome, ask, welcome, ask. The fiddly details of how to welcome someone live inside welcome_customer(). That's the function payoff.
def?Convention: put all def blocks near the top of your file, then write the "main program" underneath. Python doesn't mind either way, but humans read files top-to-bottom and want to know what tools exist before they see the program using them.
Try It Yourself
14 minThree tasks. Define, call, and notice how short your main program becomes.
Write a function called say_hello that prints Hello, world!. Call it three times. The whole script should be five lines or fewer.
Hint
def say_hello(): print("Hello, world!") say_hello() say_hello() say_hello()
If you ran it and saw nothing, double-check that you wrote say_hello() with the parentheses on the call lines — not just say_hello.
Write a function called divider that prints a row of 40 dashes. Then write a tiny program that prints a name, a divider, a country, a divider, and a hobby — using your function in between each.
Hint
def divider(): print("-" * 40) print("Name: Aisyah") divider() print("Country: Malaysia") divider() print("Hobby: badminton")
Notice the main program reads almost like a checklist. That's the function payoff again. If you ever want longer dividers, change 40 to 60 in one place.
Write a function show_menu that prints three menu items, each on its own line with a number in front — like 1. roti canai. Then ask the user with input("Choose 1-3: "). After they type, call show_menu() again and print You chose: followed by their answer. Calling the function twice should print the same menu twice — no copy-paste.
Hint
def show_menu(): print("1. roti canai") print("2. nasi lemak") print("3. teh tarik") show_menu() choice = input("Choose 1-3: ") show_menu() print("You chose:", choice)
The big win here: the menu lives in one place. When you add a fourth item next week, you change show_menu once and both prints update automatically.
Mini-Challenge · Pranav's Silent Script
8 minPranav says his program is broken — "it runs but nothing prints!" Read his code, spot the two bugs, and fix them.
# pranav_intro.py — runs but stays silent
def intro()
print("Hi, I'm Pranav.")
print("I'm 12 years old.")
print("I like cricket.")
intro- Bug 1. Look at the
defline — what tiny character is missing at the end? - Bug 2. The very last line is supposed to call the function, not just name it. What does it need on the end?
Show one possible fix
# pranav_intro.py — fixed def intro(): print("Hi, I'm Pranav.") print("I'm 12 years old.") print("I like cricket.") intro()
Two of the most common first-week function bugs in one file. The missing : on the def line causes a SyntaxError. The missing () on the call line causes no error at all — the program runs perfectly and prints nothing, which is even more confusing. Memorise the shape: def name(): when defining, name() when calling.
Recap
3 minA function is a named recipe. def name(): writes the recipe; name() cooks it. The body of the function is everything indented underneath the def line, and Python uses that indentation to tell the function's instructions apart from the rest of the file. Defining a function doesn't run it — you must call it to see anything happen. The payoff is that your main program shrinks down to a readable list of high-level steps, and any change to how a step works happens in just one place. Next lesson we'll teach functions to accept data from the caller.
Vocabulary Card
def- The Python keyword that begins a function definition. Always followed by the name, parentheses and a colon.
- function
- A named block of code you can run on demand. Defined once, called as many times as you like.
- call (a function)
- To actually run a function's body, by writing its name followed by
().say_hello()calls it;say_helloalone does not. - body (of a function)
- The indented lines underneath
def. Everything in the body runs each time the function is called. - main program
- The non-indented lines that actually drive your script — usually just a series of function calls.
Homework
4 minCreate a new file about_me.py. Build a tiny self-introduction program that uses three functions.
- Define
print_divider()— prints a row of 30 equal signs. - Define
print_intro()— prints your name, age, and town on three separate lines. - Define
print_facts()— prints three fun facts about you, one per line, each starting with-. - In the main program (no indentation), call them in this order: divider, intro, divider, facts, divider.
- Notice: the main program is exactly five lines, all function calls, no print statements.
Bring about_me.py next class — in PY-L1-27 we'll upgrade these functions so they can take inputs (parameters), and the same function can introduce anyone, not just you.
Sample · about_me.py
# about_me.py — three functions, five-line main program def print_divider(): print("=" * 30) def print_intro(): print("Name: Aisyah Rahman") print("Age: 12") print("Town: Petaling Jaya") def print_facts(): print("- I play badminton on weekends.") print("- I have a cat named Mochi.") print("- I'm learning Python at the Hub.") # main program print_divider() print_intro() print_divider() print_facts() print_divider()
The point isn't the facts — it's the shape. Three def blocks at the top, then a main program that's pure function calls. Read the bottom of the file and you can tell what the program does without scrolling up. That's the trade we just made.