Defining 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.2.1 Create functions using the def keyword
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
Function Syntax
# Defining a function
def greet(name): # def keyword, function name, parameters
"""Greets a person by name.""" # Docstring (optional)
print(f"Hello, {name}!")
# Calling a function
greet("Ali") # Hello, Ali!
greet("Dana") # Hello, Dana!
# Function with no parameters
def say_hello():
print("Hello, World!")
say_hello() # Hello, World!Parameters & Arguments
# Multiple parameters
def add(a, b):
return a + b
result = add(10, 20) # 30
# Default parameter values
def power(base, exp=2):
return base ** exp
print(power(5)) # 25 — uses default exp=2
print(power(5, 3)) # 125 — overrides exp=3
# Keyword arguments
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Ali") # Hello, Ali!
greet("Ali", greeting="Hi") # Hi, Ali!
greet(greeting="Hey", name="Dana") # Hey, Dana!Return Values
# Return a single value
def square(n):
return n ** 2
result = square(5) # 25
# Return multiple values (as tuple)
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
q, r = divide(17, 5)
print(f"17 ÷ 5 = {q} remainder {r}") # 17 ÷ 5 = 3 remainder 2
# Return vs Print
def bad_add(a, b):
print(a + b) # Prints but returns None!
def good_add(a, b):
return a + b # Returns the value
x = bad_add(3, 4) # Prints 7, but x = None!
y = good_add(3, 4) # y = 7| Concept | Description | Example |
|---|---|---|
| Parameter | Variable in function definition | def f(x): — x is parameter |
| Argument | Value passed in function call | f(5) — 5 is argument |
| Return | Send a value back to caller | return x + 1 |
| None | Returned if no explicit return | Functions with only print() |
return vs print
return sends a value back to the code that called the function. print()
just displays text on screen. A function that print()s without
returning gives None when you try to use its result.
Worked Examples
1 Temperature Converter
def celsius_to_fahrenheit(c):
return c * 9/5 + 32
def fahrenheit_to_celsius(f):
return (f - 32) * 5/9
temp = float(input("Temperature: "))
unit = input("C or F? ").upper()
if unit == "C":
result = celsius_to_fahrenheit(temp)
print(f"{temp}°C = {result:.1f}°F")
else:
result = fahrenheit_to_celsius(temp)
print(f"{temp}°F = {result:.1f}°C")2 Grade Calculator
def get_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
def get_feedback(grade):
feedback = {
"A": "Excellent!", "B": "Good job!",
"C": "Satisfactory", "D": "Needs improvement",
"F": "Please see the teacher"
}
return feedback.get(grade, "Unknown")
score = int(input("Enter score: "))
grade = get_grade(score)
print(f"Grade: {grade} — {get_feedback(grade)}")3 Input Validation Function
def get_int(prompt, low=None, high=None):
"""Get a valid integer from user within optional range."""
while True:
try:
value = int(input(prompt))
if low is not None and value < low:
print(f"Must be at least {low}")
elif high is not None and value > high:
print(f"Must be at most {high}")
else:
return value
except ValueError:
print("Please enter a valid integer")
age = get_int("Enter age (1-120): ", 1, 120)
print(f"Your age is {age}")Pitfalls & Common Errors
Calling Before Defining
You must define a function before calling it. Python reads top to bottom —
calling greet() above its def causes NameError.
Forgetting return
If your function doesn't have a return statement, it returns None.
Writing x = my_func() where my_func only prints gives
x = None.
Forgetting Parentheses
greet is the function object. greet() actually calls it. Without
(), the function is not executed.
Pro-Tips for Exams
Function Tips
- A function should do one thing well — keep functions focused
- Use return for values you need to use later; print for output to screen
- Default parameters must come after required parameters
- A function stops executing at the first
returnit reaches - Use descriptive function names:
calculate_average()notcalc()
Graded Tasks
What are the 3 parts of a function definition? What is the difference between a parameter and an argument?
Explain why x = print("hello") sets x to None.
Write a function is_even(n) that returns True if n is even, False otherwise.
Write a function factorial(n) that returns n! using a loop.
Trace: def f(x, y=2): return x * y. What is f(3)?
f(3, 4)? f(y=5, x=2)?
Create a mini-calculator with separate functions for addition, subtraction, multiplication, and division. Use a menu loop.
Self-Check Quiz
def f(x) and
f(5)?