Defining Functions

Concepts covered: Functions

A function is a named block of code you can run from anywhere in a program, so the same logic never has to be written twice.

Calling a function

Every time you write print("Hello") or len("text"), you're calling a function. These are built-in functions that come with Python, created by Python developers to handle common tasks. The print() function displays output to the screen. The len() function calculates the length of a string or collection. You do not need to know how these functions work internally; you just need to know what to give them and what they give back.

# Using built-in functions you already know
message = "Hello, Python!"
print(message)
print(len(message))

# More built-in functions
numbers = [5, 2, 8, 1, 9]
print(max(numbers))
print(min(numbers))
print(sum(numbers))

Output:

Hello, Python!
14
9
1
25

Each function call follows the same pattern: write the function name, open parentheses, provide any data the function needs (called arguments), and close parentheses. The function processes the arguments and may produce a result you can use.

Functions for your own rules

Built-in functions cover common operations, but your programs have unique requirements. You might need to calculate taxes for your specific business rules, format names according to your company standards, or validate data in ways Python can't predict. Creating your own functions lets you package this custom logic and reuse it throughout your program.

Consider a program that needs to calculate the area of rectangles in several places. Without functions, you would repeat the calculation each time:

# First calculation
width1 = 5
height1 = 3
area1 = width1 * height1
print("Room 1 area:", area1)

width2 = 10
height2 = 4
area2 = width2 * height2
print("Room 2 area:", area2)

width3 = 7
height3 = 6
area3 = width3 * height3
print("Room 3 area:", area3)

The calculation width * height appears 3 times. That looks harmless until the formula changes, say to add a margin for waste or to convert units, and you have to update every place you copied it. A function holds the logic in one place, and you call it from anywhere.

To create a function, use the def keyword (short for "define") followed by the function name with parentheses after it, and end the line with a colon. The lines of code that belong to the function must be indented. This indented block is called the function body, and it contains the code that runs when you call the function.

# Define a simple function
def greet():
    print("Hello, World!")
    print("Welcome to Python functions!")

print("Before calling the function")

greet()

print("After calling the function")

Output:

Before calling the function
Hello, World!
Welcome to Python functions!
After calling the function

Notice the order of output. The code inside the function only runs when you call it with greet(). You can call a function as many times as you want, and each call executes the function body from the beginning.

def announce():
    print("*" * 20)
    print("IMPORTANT MESSAGE")
    print("*" * 20)

announce()
print("First message")
announce()
print("Second message")
announce()

Output:

********************
IMPORTANT MESSAGE
********************
First message
********************
IMPORTANT MESSAGE
********************
Second message
********************
IMPORTANT MESSAGE
********************

Parts of a function definition

Every function definition has the same structure, and knowing the parts makes your own functions easier to get right and other people's code easier to read:

def function_name():
    # Function body
    # Indented
    statement_1
    statement_2
    statement_3

# Outside function

Function naming conventions

Function names follow the same rules as variable names. They must start with a letter or the _ character, and digits are allowed after that. Python keywords are off limits. On top of those rules, Python code follows strong conventions that keep names readable:

Good function names
  • calculate_area
  • format_user_name
  • validate_email
  • convert_temperature
  • get_total_price
Poor function names
  • doStuff
  • f
  • myFunction
  • process
  • x

Good function names use snake_case, which means all lowercase with _ between words. They use verbs or verb phrases that describe what the function does. Someone reading calculate_area immediately understands the purpose without looking at the code inside.

Indentation is mandatory

Python uses indentation to determine which code belongs to a function. Every line in the function body must be indented by the same amount (typically 4 spaces). Inconsistent indentation causes errors:

# CORRECT: Consistent indentation
def greet():
    print("Hello!")
    print("Welcome!")
    print("Have a great day!")

# WRONG: Would cause IndentationError
def greet_broken():
    print("Hello!")
  # Error! Wrong indentation
  print("This line has wrong indentation!")
    print("Have a great day!")

When you reduce the indentation back to the original level, you signal the end of the function body. The next unindented line is outside the function and runs independently of any function call.

Most of any professional Python codebase is function definitions and the calls that combine them.

Python uses indentation to mark the function body, and that body runs only when you call the function, not when you define it.

Prefer calculate_tax to multiply_by_rate, because the first name still fits if the tax calculation changes and the second exposes an implementation detail.

About this lesson

This section is part of the Functional Programming: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.