Defining functions

As programs grow, we quickly run into repetition. The same small pieces of logic start appearing in multiple places, especially when we generate output, transform data, or assemble pages. Functions exist to give these repeated ideas a name and a shape, so we can reuse them confidently as our programs expand into more capable systems.

What a function is and why functions are useful

A function is a named block of code that performs a specific piece of work. Once defined, it can be used whenever that work is needed.

Functions help us reduce repetition, make intent clearer, and keep related statements together. Instead of thinking about individual lines, we can think in terms of meaningful operations that our program performs.

Defining a function using def

In Python, a function is defined using the def keyword, followed by a name and a pair of parentheses. The function body is indented beneath the definition.

def render_header():
    return "<h1>Planets of the Solar System</h1>"

This definition tells Python what the function does, but it does not run the code inside it yet.

Naming functions

Function names describe actions. They usually read like verbs or verb phrases and follow the same naming rules as variables.

Clear names make code easier to scan and understand later, especially when functions are used throughout a program.

def generate_planet_list():
    return "<ul><li>Mars</li><li>Jupiter</li></ul>"

Calling a function

Calling a function means asking Python to run the code inside it. This is done by writing the function’s name followed by parentheses.

html = render_header()
print(html)

When the function is called, its body runs, and any returned value is produced at the call site.

Using functions to group related statements

Functions allow us to collect related statements into a single, named unit. This makes larger programs easier to reason about and modify.

def build_page():
    header = render_header()
    body = generate_planet_list()
    return header + body

Here, the function groups together the steps needed to build part of an HTML page. The surrounding program can now focus on when a page is built, rather than how each piece is assembled.

Conclusion

At this point, we know what functions are, why they matter, and what defining and calling one looks like in practice. We can recognize how functions help organize growing Python programs and support reuse as we build more structured and capable systems.