Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 5 · Python Functions

Python Functions

Conditions and loops describe the steps of a task. When those steps form a useful operation, a function gives that operation a name so it can be called again.

On this pageCreating a FunctionCalling a Function

A function is a reusable block of code that performs a specific task. It only runs when called, which helps avoid repeating the same instructions throughout a program. Functions also make code easier to organize and maintain.

Creating a Function

In Python, a function is defined using the def keyword, followed by its name and parentheses ().

def say_hello():
    print("Hello, welcome to Python!")
Listing 191 — Creating a Function

This creates a function named say_hello that prints a greeting message. Indentation is here important as it shows which lines belong inside the function.

Calling a Function

To run the function, simply write its name followed by parentheses:

say_hello()
Listing 192 — Calling a Function

Output

Hello, welcome to Python!

You can call it as many times as needed:

say_hello()
say_hello()
say_hello()
Listing 193 — Calling a Function

Output

Hello, welcome to Python!
Hello, welcome to Python!
Hello, welcome to Python!

Functions are one of Python’s most useful tools — they make your code cleaner, shorter, and easier to reuse.