Skip to content
Kuza Ndoto Academy

Defining Functions

Beginner → IntermediateChapter 5 · Page 25 of 564 min readUpdated 15 Nov 2026

A function is a named block of code that performs one job. You write it once, then run it whenever you need it by calling its name. Functions keep programs short, organised and easy to fix, and they are the main building block of every serious Python project.

Why use functions?

  • Reuse: write code once and call it many times instead of copying and pasting it. Programmers call this the DRY principle: Don't Repeat Yourself.
  • Organisation: split a big problem into small, named steps such as calculate_total() and print_receipt().
  • Easier fixes: if there's a bug, you fix it in one place and every call benefits.
  • Readability: a good function name explains what the code does without the reader studying every line.

You've already used plenty of built-in functions: print(), len(), input(), sum(). Now you'll write your own.

Defining and calling a function

Use the def keyword, a name, brackets and a colon. The indented lines below form the function's body.

def greet():
    print("Habari!")
    print("Karibu Kuza Ndoto.")

greet()
greet()
Habari! Karibu Kuza Ndoto. Habari! Karibu Kuza Ndoto.

Defining a function doesn't run it; it only teaches Python what greet means. The body runs each time you call the function by writing its name followed by brackets: greet().

How Python moves through a program with functions

When Python reaches a call, it jumps into the function, runs the body from top to bottom and then comes back to the line after the call.

def make_tea():
    print("Boil water")
    print("Add tea leaves and milk")

print("Morning routine starts")
make_tea()
print("Drink tea")
Morning routine starts Boil water Add tea leaves and milk Drink tea

Removing repetition

Here a small function draws a divider line that is needed several times.

def divider():
    print("-" * 20)

divider()
print("KUZA STORES RECEIPT")
divider()
print("Exercise books x3: KES 150")
divider()
-------------------- KUZA STORES RECEIPT -------------------- Exercise books x3: KES 150 --------------------

If you later decide the line should be 30 characters long, you change one line inside divider() instead of three lines scattered through the program.

A first look at parameters and return

Most useful functions take some input and give back a result. The names inside the brackets of the def line are parameters: variables that receive values when the function is called. return sends a result back to the caller.

def greet_person(name):
    print(f"Habari, {name}!")

def area_of_rectangle(length, width):
    """Return the area of a rectangle."""
    return length * width

greet_person("Wanjiku")
greet_person("Otieno")

plot = area_of_rectangle(20, 15)
print("Plot area:", plot, "square metres")
Habari, Wanjiku! Habari, Otieno! Plot area: 300 square metres
Call area_of_rectangle(20, 15) in Function body length = 20 width = 15 return length * width out Return value: 300 stored in plot The call is replaced by its return value, so the line becomes plot = 300
Figure 1. Arguments flow into the parameters, the body does the work and return sends one value back to the place where the function was called.

Both ideas get their own pages: Parameters & Arguments and Return Values.

Documenting functions with docstrings

The triple-quoted string on the first line of area_of_rectangle is a docstring. It describes what the function does. Editors such as VS Code show it when you hover over the function name, and you can read it in code through the function's __doc__ attribute.

print(area_of_rectangle.__doc__)
Return the area of a rectangle.

A good docstring is a short sentence in the imperative ("Return…", "Calculate…", "Print…"). For bigger functions, add more lines describing the parameters and the result.

Naming and placeholders

  • Function names follow the same rules as variables; use lowercase snake_case.
  • Since functions do things, start names with a verb: calculate_fees(), send_reminder(), is_valid_pin().
  • Need a function you haven't written yet? Use pass as its body so the program still runs (see Break, Continue & Pass).
def send_sms_reminder():
    pass    # TODO: connect to an SMS service later

send_sms_reminder()    # runs, does nothing yet
Common mistake

Calling a function before defining it. Python runs a file from top to bottom, so the def must run before the first call. If you call say_hi() on line 1 and define it on line 5, you get a NameError. Put function definitions near the top of your file.

Common mistake

Forgetting the brackets. greet without brackets doesn't call the function; it just refers to it. print(greet) shows something like <function greet at 0x...> (the number is a memory address and differs every run). Write greet() to run it.

Key points

  • Define a function with def name(): and an indented body; call it with name().
  • Defining a function doesn't run it; each call runs the body once and then returns to the caller.
  • Functions remove repetition, organise code and make bugs easier to fix.
  • Parameters receive input and return sends results back.
  • Document functions with a docstring and give them clear, verb-based names.
Up next · FunctionsParameters & ArgumentsPass information into functions.
→

Tip: use the ← and → keys to move between pages.