Module 05 — Functions
Packaging logic into reusable, named blocks — the single biggest step toward organized code.
Prerequisite: Module 04 — Control Flow & Loops
After this lesson, you will be able to
- Define a function with def and call it with arguments
- Understand the difference between return and print inside a function
- Use default parameter values
- Explain the difference between local and global variable scope
Concept & Syntax
A function is a named, reusable block of code that performs a task. You've already been
using one — print() — without writing it yourself. Once you learn to write your own, you can take
any block of logic you'd otherwise copy-paste, give it a name, and call it as many times as you like.
The most important beginner distinction is return vs. print: print() only
displays something on screen and is gone forever; return hands a value back to whoever called the
function, so that value can be stored, passed along, or used in further calculations.
def function_name(parameter1, parameter2="default"):
"""Optional docstring explaining what this does."""
result = parameter1 + parameter2
return resultExamples
A function with no return value Very Easy
def say_hello():
print("Hello!")
say_hello()
say_hello()Calling say_hello() twice runs the function's body twice. It has no parameters and returns nothing (technically it returns None).
Parameters and return Easy
def add(a, b):
return a + b
total = add(4, 5)
print(total)a and b are parameters — placeholders filled in by the arguments 4 and 5 when the function is called. return hands the sum back so it can be stored in total.
Default parameters Intermediate
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Sam"))
print(greet("Sam", "Hi"))greeting has a default value, so it's optional. Supplying a second argument overrides the default.
A function calling another function Real World
def square(n):
return n * n
def sum_of_squares(a, b):
return square(a) + square(b)
print(sum_of_squares(3, 4))Functions can call other functions — this is how complex programs stay organized into small, testable pieces.
Recursion: Fibonacci Challenge
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
for i in range(8):
print(fibonacci(i), end=" ")A recursive function calls itself with a smaller input until it reaches a 'base case' (here, n <= 1) that stops the recursion.
Visual Explanation
🔍 What happens internally? (advanced)
Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory — which is exactly what the memory panel in the tracer above is showing you.
Watch a function call, run, and return
Use the controls below to run this example one line at a time and watch the interpreter's memory update live.
Code
def greet(name):
message = "Hello, " + name
return message
result = greet("Ada")
print(result)
Interpreter state
Console output
Common Mistakes
A function that prints instead of returning can't have its result used later — printing is not the same as producing a value.
def add(a, b):
print(a + b)
total = add(2, 3)
print(total * 2)def add(a, b):
return a + b
total = add(2, 3)
print(total * 2)A variable created inside a function only exists inside that function (local scope) — it disappears once the function ends.
def set_name():
name = "Ada"
set_name()
print(name)def set_name():
return "Ada"
name = set_name()
print(name)- Give functions verb-based names describing what they do: calculate_total(), not data2().
- A function should do one thing well — split large functions into smaller ones.
- Prefer return over relying on global variables to pass data out of a function.
- Add a short docstring to non-trivial functions explaining what they do.
Exercise & Challenge
Exercise 1 — Write code
Write a function called is_even(n) that returns True if n is even and False otherwise. What does is_even(7) return?
🏆 Challenge
Write a function greatest(a, b, c) that returns the largest of three numbers, without using the built-in max().
- Use only if/elif/else comparisons
- Handle ties (equal numbers) sensibly
- Test it with at least 3 different calls
💡 Need a hint?
Start by assuming a is the greatest, then compare it against b, then against c.
🔍 Show a sample solution
def greatest(a, b, c):
biggest = a
if b > biggest:
biggest = b
if c > biggest:
biggest = c
return biggest
print(greatest(4, 9, 2))Quiz
Answer every question, then submit to see your score and explanations.
1. What's the key difference between return and print inside a function?
2. What happens to a variable created inside a function once the function finishes?
3. In def greet(name, greeting="Hello"): , what is greeting?
4. What must every recursive function have to avoid infinite recursion?
5. What does a function return if it has no explicit return statement?
Summary
- def creates a reusable, named block of code; parentheses hold its parameters.
- return hands a value back to the caller; print only displays it.
- Default parameter values make arguments optional.
- Variables created inside a function are local and disappear once it returns.