Functions
def, calling, and why functions exist.
4 minute read
Big idea
A function is a named block of code you write once and run whenever you call it by name.
Defining and calling
def greet():
print("Hello!")
print("Welcome to Python.")
def— "define a function".greet— its name (snake_case, like variables).():— the parentheses and colon. The indented block below is the function's body.
Defining a function doesn't run it. Calling it does — its name followed by ():
def greet():
print("Hello!")
print("Welcome to Python.")
greet()
print("---")
greet()output
Hello!
Welcome to Python.
---
Hello!
Welcome to Python.Run and edit it in the app.
Giving it something to work with
A name in the parentheses is a parameter: a variable that gets its value from the call.
def cheer(name):
print(f"Go, {name}!")
cheer("Ada")
cheer("Grace")What does it print? Show the answer
Go, Ada!
Go, Grace!Run and edit it in the app.
The value you pass in — "Ada" — is called the argument.
Why bother?
- No copy-paste. Fix a bug once, and every call is fixed.
- Names explain code.
print_receipt(order)says what happens without reading every line. - Small pieces. A big program becomes many short functions you can test one at a time.
Order matters
Python reads top to bottom, so a function must be defined before the line that calls it runs:
say_hi()
def say_hi():
print("Hi!")output
Hi!Run and edit it in the app.
NameError: name 'say_hi' is not defined — at the moment of the call, Python hadn't reached the def yet. Move the call below it.
Docstrings
A string on the first line of the body documents what the function does. Tools and editors show it when you hover the name:
def area(width, height):
"""Return the area of a rectangle."""
return width * height
(return is next lesson.)
A file contains only def hello(): print('hi') — what does running it print?
Watch it
Think of it like
A recipe card titled "Pancakes". Writing the card doesn't make pancakes. Saying "make Pancakes" — calling it — does, as many times as you like.
Key terms
- Function — A named, reusable block of code.
- Call — Running a function:
greet(). - Parameter / argument — The name in the definition / the value passed in the call.
Check yourself
Which keyword defines a function?
When does a function's body run?
Why does calling a function above its def fail?