Functions
A function is a reusable block of code that performs a specific task. Functions make programs shorter, more organized, and easier to debug by breaking complex problems into smaller, named pieces.
Learning Objectives
- 11.3.1.1 Write code in a programming language using functions
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.
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 `max_of_three(a, b, c)` that returns the largest of three numbers.
Create a calculator program using separate functions for add, subtract, multiply, and divide.