User-Defined Functions
A function is a reusable block of code that performs a specific task. Functions make programs modular, testable, and easier to debug by breaking complex problems into smaller, named procedures with explicit parameters, return values, and variable scopes.
Learning Objectives
- 11.3.1.1 Write code in a programming language using functions
- 11.3.1.2 Assign function parameters
- 11.3.1.3 Define the scope of variables (local vs global)
- 11.3.3.4 Solve applied problems from various subject areas
Conceptual Anchor
The Recipe Analogy
A function is like a recipe: you define it once (write the recipe), then use it whenever needed (cook the dish). The ingredients are parameters, and the finished dish is the return value. You don't rewrite the recipe every time you cook — you just call it by name!
Rules & Theory
Defining & Calling
# Defining a function
def greet(name): # def keyword, function name, parameters
"""Greets a person by name."""
print(f"Hello, {name}!")
# Calling a function
greet("Ali") # Hello, Ali!
greet("Dana") # Hello, Dana!Return Values
def add(a, b):
# 'return' sends the result back to where the function was called
return a + b
result = add(5, 3)
print(result) # 8
# Without return, result is None
def bad_add(a, b):
print(a + b)
x = bad_add(5, 3) # Prints 8
print(x) # None (because nothing was returned)Default Arguments
You can set default values for parameters. If the caller doesn't provide a value, the default is used.
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (3^2)
print(power(3, 3)) # 27 (3^3)Worked Examples
1 Temperature Converter
def celsius_to_fahrenheit(c):
return c * 9/5 + 32
temp = float(input("Enter temperature in C: "))
f_temp = celsius_to_fahrenheit(temp)
print(f"{temp}C is {f_temp}F")2 Validation Function
def get_positive_integer(prompt):
while True:
try:
value = int(input(prompt))
if value > 0:
return value
else:
print("Must be positive!")
except ValueError:
print("Please enter a number.")
age = get_positive_integer("Enter your age: ")
print(f"You are {age} years old.")Pitfalls & Common Errors
Forgetting ()
greet is the function object. greet() calls the function. Without
parentheses, nothing happens.
Indentation Error
The body of the function must be indented. Unindented code is considered outside the function.
UnboundLocalError with Global Variables
If you reassign a global variable inside a function without the global keyword, Python treats it as a local variable before initialization, raising an UnboundLocalError.
Scope of Variables (11.3.1.3)
| Scope | Where Defined | Accessibility | Lifetime |
|---|---|---|---|
| Local | Inside a function body or as a parameter | Only within that specific function | Created on call, destroyed when function returns |
| Global | Outside all functions (top-level) | Everywhere in the file (read-only unless global used) |
Persists until the program terminates |
Pro-Tips for Exams
Exam Checklist
- Functions without an explicit
returnstatement returnNoneby default. - Default parameters must follow positional parameters:
def func(a, b=10):is valid, butdef func(a=10, b):is a SyntaxError. - Avoid mutable default arguments like
def add(item, lst=[]):— useNoneinstead.
Graded Tasks
What keyword is used to define a function? What keyword returns a value?
Explain the difference between print(result) inside a function vs return result.
Write a function is_prime(n) that returns True if $n$ is prime, and False otherwise.
Predict the output of modifying a global variable inside a function with and without the global declaration.
Create a modular banking system: separate functions for deposit(), withdraw(), and check_balance() validating user inputs.
Self-Check Quiz
return statement?