Defining and calling functions
🌍 In real life. A recipe card for "masala tea" is written once and kept in a drawer. Writing the card doesn't make any tea. Every time someone says "make masala tea", the cook takes out the card and follows it again, step by step.
A function is a recipe card for code: write the steps once, give them a name, and run them whenever you call that name.
The idea in one sentence: def name(): stores a block of code under a name without running it, and name() runs that block each time you call it.
Its words:
- function: a named block of code
- define: write the function with
def; this only stores it - body: the indented lines under the
defline - call: run the function by writing its name with brackets,
greet()
Step by step, for the code below:
- Python reads
def greet():and stores the body under the namegreet. Nothing is printed yet. - It reaches
greet(): it jumps into the body and runs its lines. - When the body ends, Python comes back to the line after the call and carries on.
def greet():
print("Hello!")
print("Welcome to Python.")
greet()
greet()Why functions? A name for a job makes code shorter (write it once, call it many times), easier to read (box() says what it does) and easier to fix (a bug in the recipe is fixed in one place). Defining a function costs almost nothing; each call costs as much as running its body.
Python reads from top to bottom, so a function must be defined before you call it:
hello()
def hello():
print("hi")Functions can call other functions. That lets you build something big out of small, named pieces:
def line():
print("-" * 12)
def box():
line()
print("| Python! |")
line()
box()Mistakes and edge cases.
- Calling before defining.
hello()abovedef hello():givesNameError: name 'hello' is not defined(above). - Forgetting the brackets.
print(greet)shows something like<function greet at 0x...>, andgreeton its own line does nothing at all. Onlygreet()runs it. - An empty or unindented body.
def f():with no indented line under it givesIndentationError: expected an indented block after function definition on line 1. - Expecting def to run the body. Defining only stores the recipe; nothing happens until the call.
Quiz
What does this print?
def say(): print("hi") say() say()What does this print?
def f(): print("A") print("B")What does
defdo?- It creates a function, without running its body yet
- It runs the function's body straight away
- It deletes a function
What does this print?
def a(): print("a") def b(): a() print("b") b() a()Which line has a mistake?
def greet() print("hi") greet()
Coding tasks
Define a function called
hellothat printsHello, Python!. Then call it twice.Define
line()that prints=====, andbanner()that callsline(), printsHELLO, and callsline()again. Then callbanner()once.