Functions
Functions are reusable recipes for your code — learn parameters, return values, scope, and when to write your own instead of repeating yourself.
The McDonald's lesson in reusability
In 1948, the McDonald brothers redesigned their restaurant around one idea: a system where every burger was made the same way, every time. They did not reinvent the burger for each customer. They wrote a recipe once — specific ingredients, specific steps, specific timing — and then followed it thousands of times a day. Any new employee could learn the recipe and produce the exact same result.
That is what a function is in programming. A function is a recipe: a named block of code you write once and use whenever you need it. Instead of copying and pasting the same 10 lines of code in five places, you write a function once and call it five times.
The McDonald brothers' system turned a small restaurant into a global empire. Functions turn messy, repetitive code into clean, professional software.
# Without a function — copy-pasted code
print("=" * 30)
print("RECEIPT")
print("=" * 30)
# ... 50 lines later, you need the same header again
print("=" * 30)
print("RECEIPT")
print("=" * 30)
# With a function — write once, use anywhere
def print_header():
print("=" * 30)
print("RECEIPT")
print("=" * 30)
print_header() # First use
print_header() # Second use — no duplication
Anatomy of a function
A function has four parts:
def greet(name): # def, name, parameter
message = f"Hello, {name}!" # body — the work
return message # return value — the output
result = greet("Sarah") # calling the function
print(result) # Hello, Sarah!
| Part | What it is | Analogy |
|---|---|---|
def | Keyword that starts a function definition | "Here is a new recipe" |
| Function name | What you call it (greet) | Recipe title ("Chocolate Cake") |
| Parameters | Inputs the function needs (name) | Ingredients ("2 cups flour") |
return | The output the function produces | The finished dish |
Step 1: Define — Use def to create the function. This does NOT run the code — it just saves the recipe.
Step 2: Call — Use the function name with parentheses: greet("Sarah"). NOW the code runs.
Step 3: Receive — The return value comes back to wherever you called the function. Store it in a variable or use it directly.
Parameters and arguments
Parameters are the variables listed in the function definition. Arguments are the actual values you pass when calling it.
def calculate_tip(bill, tip_percent): # bill and tip_percent are parameters
tip = bill * (tip_percent / 100)
total = bill + tip
return total
result = calculate_tip(50.00, 20) # 50.00 and 20 are arguments
print(f"Total: ${result:.2f}") # Total: $60.00
Default parameters
You can give parameters default values so callers do not always have to specify them:
def calculate_tip(bill, tip_percent=18): # 18 is the default
tip = bill * (tip_percent / 100)
return bill + tip
print(calculate_tip(50)) # Uses default 18% → $59.00
print(calculate_tip(50, 25)) # Overrides with 25% → $62.50
Keyword arguments
When a function has multiple parameters, you can name them explicitly for clarity:
def create_user(name, age, city):
print(f"{name}, {age}, from {city}")
# Positional — order matters
create_user("Alice", 30, "London")
# Keyword — order does not matter
create_user(city="Tokyo", name="Bob", age=25)
There Are No Dumb Questions
"What is the difference between
print()andreturn?"
print()displays text on the screen — it is for humans to read.returnsends a value back to the calling code — it is for your program to use. A function thatreturnproduces no usable output. A function thatreturns but does notreturn, then"Can a function return multiple values?"
Yes. Use a comma:
return tip, total. Python packs them into a tuple. Unpack them:tip, total = calculate_tip(50). This is a very common Python pattern.
Write Your First Function
25 XPReturn values — functions that produce output
A function without return returns None — Python's way of saying "nothing."
def greet(name):
print(f"Hello, {name}!") # Prints but returns nothing
result = greet("Alice")
print(result) # None
def calculate_area(length, width):
return length * width # Returns a usable value
area = calculate_area(5, 3)
print(area) # 15
You can use return values directly in expressions:
def double(n):
return n * 2
print(double(5) + double(3)) # 10 + 6 = 16
Early return — exit a function early
def divide(a, b):
if b == 0:
return "Error: cannot divide by zero"
return a / b
print(divide(10, 3)) # 3.333...
print(divide(10, 0)) # Error: cannot divide by zero
Scope — where variables live and die
Scope is about where a variable exists. Think of it like rooms in a house: a lamp in the bedroom only lights up the bedroom, not the kitchen.
name = "Global Alice" # Global scope — accessible everywhere
def greet():
name = "Local Bob" # Local scope — only exists inside this function
print(name) # "Local Bob"
greet()
print(name) # "Global Alice" — unchanged
✗ Without AI
- ✗Created outside any function
- ✗Accessible everywhere in the file
- ✗Lives for the entire program
- ✗Think: house-wide lighting
✓ With AI
- ✓Created inside a function
- ✓Only accessible inside that function
- ✓Dies when the function ends
- ✓Think: bedroom lamp
There Are No Dumb Questions
"Why does Python delete local variables when a function ends?"
Memory management. If every variable from every function call lived forever, your program would eventually run out of memory. Local variables are like scratch paper — you use them to solve a problem, then throw them away. The
returnvalue is the answer you keep."What if I need a function to remember something between calls?"
For now, return the value and pass it back in next time. Later, you will learn about classes (objects that bundle data and functions together). For this course, parameters and return values are all you need.
Built-in functions you already know
Python comes with dozens of built-in functions. You have been using some already:
# Type conversion
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
bool(0) # False
# Math
len("Hello") # 5 (length)
max(3, 7, 1) # 7
min(3, 7, 1) # 1
abs(-5) # 5 (absolute value)
round(3.7) # 4
sum([1, 2, 3, 4]) # 10
# Input/Output
print("Hello") # Display text
input("Name: ") # Get user input
# Utility
type(42) # <class 'int'>
range(5) # 0, 1, 2, 3, 4
sorted([3, 1, 2]) # [1, 2, 3]
Function Composition
25 XPPutting it together — a password validator
Here is a practical function that combines everything from this module:
def validate_password(password):
if len(password) < 8:
return "Too short — must be at least 8 characters"
has_upper = False
has_digit = False
for char in password:
if char.isupper():
has_upper = True
if char.isdigit():
has_digit = True
if not has_upper:
return "Must contain at least one uppercase letter"
if not has_digit:
return "Must contain at least one digit"
return "Password is valid!"
# Test it
print(validate_password("short")) # Too short
print(validate_password("alllowercase1")) # No uppercase
print(validate_password("NoDigits")) # No digit
print(validate_password("GoodPass1")) # Valid!
This function uses: parameters, return values, early returns, a for loop, if statements, string methods, and a boolean pattern. Every concept from modules 1-4 in one real function.
Build a BMI Calculator
50 XPKey takeaways
- Functions are reusable recipes — write once, call many times, update in one place
defdefines a function, calling it (with parentheses) runs it — defining is NOT running- Parameters are inputs; return values are outputs — this is how functions communicate
- Default parameters let callers skip arguments:
def greet(name="World") returnsends a value back to the caller;print()just displays text — they are not interchangeable- Scope: local variables die when the function ends; communicate through parameters and returns, not globals
- Built-in functions like
len(),sum(),max(),sorted()save you from reinventing the wheel
Knowledge Check
1.What is the output of this code? ```python def add(a, b): return a + b result = add(3, 4) print(result) ```
2.What does a function return if it has no `return` statement?
3.What is the output? ```python x = 10 def change(): x = 20 print(x) change() print(x) ```
4.Which of the following correctly uses a default parameter?