PyComplete Python Course
Beginner 50 min

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.

Syntax
def function_name(parameter1, parameter2="default"):
    """Optional docstring explaining what this does."""
    result = parameter1 + parameter2
    return result

Examples

A function with no return value Very Easy

A function with no return value
def say_hello():
    print("Hello!")
 
say_hello()
say_hello()
OutputHello! 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

Parameters and return
def add(a, b):
    return a + b
 
total = add(4, 5)
print(total)
Output9

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

Default parameters
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"
 
print(greet("Sam"))
print(greet("Sam", "Hi"))
OutputHello, Sam! Hi, Sam!

greeting has a default value, so it's optional. Supplying a second argument overrides the default.

A function calling another function Real World

A function calling another function
def square(n):
    return n * n
 
def sum_of_squares(a, b):
    return square(a) + square(b)
 
print(sum_of_squares(3, 4))
Output25

Functions can call other functions — this is how complex programs stay organized into small, testable pieces.

Recursion: Fibonacci Challenge

Recursion: Fibonacci
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)
 
for i in range(8):
    print(fibonacci(i), end=" ")
Output0 1 1 2 3 5 8 13

A recursive function calls itself with a smaller input until it reaches a 'base case' (here, n <= 1) that stops the recursion.

Visual Explanation

Function is called with argumentsArguments fill the parametersFunction body runsreturn produces a valueValue goes back to the caller
The life of a single function call.
🔍 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

Code
def greet(name):
    message = "Hello, " + name
    return message
 
result = greet("Ada")
print(result)

Interpreter state

Console output

Common Mistakes

✗ Common mistake 1

A function that prints instead of returning can't have its result used later — printing is not the same as producing a value.

✗ Avoid this
This raises TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
def add(a, b):
    print(a + b)
 
total = add(2, 3)
print(total * 2)
✓ Better approach
Fixed
def add(a, b):
    return a + b
 
total = add(2, 3)
print(total * 2)
✗ Common mistake 2

A variable created inside a function only exists inside that function (local scope) — it disappears once the function ends.

✗ Avoid this
This raises NameError: name 'name' is not defined
def set_name():
    name = "Ada"
 
set_name()
print(name)
✓ Better approach
Fixed
def set_name():
    return "Ada"
 
name = set_name()
print(name)
✓ Best practices
  • 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
Python
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?

They're identical
return hands a value back to the caller; print only displays it
print is faster
return only works in loops
return produces a usable value; print just shows text and the function's result is lost.

2. What happens to a variable created inside a function once the function finishes?

It becomes global
It's deleted — local variables don't persist outside the function
It becomes a constant
Nothing changes
Local variables exist only during that function call.

3. In def greet(name, greeting="Hello"): , what is greeting?

A required argument
A parameter with a default value
A return value
A global variable
Default parameters are optional when calling the function.

4. What must every recursive function have to avoid infinite recursion?

A print statement
A base case that stops the recursion
A while loop
A global variable
The base case is the condition that stops the function from calling itself forever.

5. What does a function return if it has no explicit return statement?

0
An empty string
None
It raises an error
Python functions implicitly return None if no return statement runs.

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.

Related lessons

Saved privately in your browser — no account needed.