How to Create Reusable Blocks of Code in Python: Absolute Beginners Tutorial

Functions are the primary tool Python gives you for writing code once and using it many times. Once you understand them, you stop copying and pasting logic and start building programs that are clean, predictable, and easy to change.

Every program you write will eventually repeat the same logic in more than one place. When that happens, you have two choices: copy the code wherever you need it, or wrap it in a function and call it by name. The second option is the right one. This tutorial walks through every piece of a Python function from scratch — the syntax, the mechanics, and the thinking behind them — with examples and exercises at every step.

What Is a Function and Why Does It Matter?

A function is a named, self-contained block of code that performs a specific task. You write the block once, give it a name, and then run it by writing that name followed by parentheses anywhere in your program. Every time you call the function, Python executes the block and gives control back to whatever line called it.

The practical benefit is that your code says what it does rather than showing every mechanical step. A line that reads calculate_tax(price) tells you immediately what is happening. Thirty lines of arithmetic that achieve the same result without a function name tell you nothing at a glance.

Note

Python already gives you hundreds of built-in functions — print(), len(), range() — that work exactly this way. When you define your own function, you are following the same pattern the language itself uses.

There are three concrete reasons to use functions. First, they eliminate repetition. When the same logic lives in one function, any fix or change only needs to happen once. Second, they give code a testable unit. You can verify that a single function produces the right output before placing it into a larger program. Third, they make programs readable. Good function names act as documentation, explaining intent without requiring the reader to trace every line.

Before writing one, it helps to see what a program looks like without functions versus with them. The following example calculates a discounted price twice without a function.

python
# Without a function — logic is repeated
price_one = 100
discount_one = 0.2
final_one = price_one - (price_one * discount_one)
print(final_one)  # 80.0

price_two = 250
discount_two = 0.1
final_two = price_two - (price_two * discount_two)
print(final_two)  # 225.0

The same calculation appears twice. If you later need to change how the discount is applied, you must find and edit both locations. With a function, the logic lives in one place.

python
# With a function — logic is defined once
def apply_discount(price, discount):
    return price - (price * discount)

print(apply_discount(100, 0.2))   # 80.0
print(apply_discount(250, 0.1))   # 225.0
code builder click a token to place it

Build a simple Python function definition that takes one parameter called name and prints a greeting:

your code will appear here...
print( return def name | greet ( ) : 'Hello', class
Why: A function definition always starts with def, followed by the function name (greet), the parameter list in parentheses (name), and a colon. The function body on the next line (here print('Hello,', name)) must be indented. class and return are valid Python keywords but serve different purposes — class creates a class definition and return sends a value back from inside a function body.

Defining Your First Function with def

Every Python function starts with the def keyword. The full syntax for the simplest possible function looks like this:

python
def say_hello():
    print("Hello from my first function!")

# Call the function
say_hello()
# Output: Hello from my first function!

Breaking down each part: def signals the start of a function definition. say_hello is the name — choose something that describes what the function does. The empty parentheses mean this function accepts no input. The colon ends the definition line. The indented line below is the function body — everything indented to the same level belongs to this function.

Pro Tip

Name functions with a verb that describes their action. calculate_total, send_email, and load_file are good names. data, stuff, and func1 tell a reader nothing. Python convention uses lowercase words separated by underscores — this style is called snake_case.

Notice that defining the function does not run it. The code inside only executes when you call the function by name with parentheses. This is important: Python reads the definition when it first encounters the def block, but waits for you to call it.

Docstrings: built-in documentation

The first statement inside a function body can be a string literal called a docstring. Python stores it as the function's documentation and tools like help() can display it. It is not required, but writing one is a strong habit to develop from the start.

python
def say_hello():
    """Print a greeting to the terminal."""
    print("Hello from my first function!")

# Access the docstring
print(say_hello.__doc__)
# Output: Print a greeting to the terminal.
Purpose
Signals the start of a function definition.
Required?
Yes — every function definition must begin with def.
Purpose
The label you use to call the function later in your code.
Convention
Lowercase words joined by underscores — snake_case. Should describe the action the function performs.
Purpose
Holds the list of parameters the function accepts. Empty parentheses mean the function takes no input.
Required?
Yes — the parentheses must appear even when there are no parameters.
Purpose
Ends the def line and tells Python that an indented block follows.
Common mistake
Forgetting the colon is one of the most frequent SyntaxError causes for beginners.
Purpose
Contains the code that runs when the function is called. All lines must be indented by the same amount.
Convention
Four spaces per indent level is the Python standard (PEP 8).
spot the bug click the line that contains the bug

The function below should print a farewell message but raises a SyntaxError. Click the line you think is wrong.

1 def say_goodbye()
2 """Print a farewell message."""
3 print("Goodbye!")
4 say_goodbye()
The fix: Add a colon at the end of line 1 so it reads def say_goodbye():. Python requires a colon at the end of every def statement to signal that an indented block follows. Without it, the interpreter raises a SyntaxError before the function body is ever reached.

Parameters, Arguments, and Return Values

A function that does the same thing every time it runs has limited use. Parameters let you pass data into a function so it can work with different values each time it is called.

Defining and using parameters

A parameter is a variable name listed inside the function's parentheses. When you call the function and pass a value, that value is called an argument. Inside the function, the parameter behaves exactly like a regular variable.

python
def greet(name):
    """Print a personalised greeting."""
    print("Hello,", name)

greet("Alice")   # Output: Hello, Alice
greet("Bob")     # Output: Hello, Bob

You can define as many parameters as needed, separated by commas. Each becomes its own local variable inside the function.

python
def describe_pet(name, animal_type):
    """Print a description of a pet."""
    print(f"{name} is a {animal_type}.")

describe_pet("Milo", "cat")   # Output: Milo is a cat.
describe_pet("Rex", "dog")    # Output: Rex is a dog.

Default parameter values

You can assign a default value to a parameter. If the caller does not supply that argument, the default is used. Parameters with defaults must come after parameters without defaults.

python
def greet(name, greeting="Hello"):
    """Print a greeting with an optional custom greeting word."""
    print(f"{greeting}, {name}!")

greet("Alice")                  # Output: Hello, Alice!
greet("Bob", "Good morning")    # Output: Good morning, Bob!

Returning a value

Many functions compute a result that the rest of your program needs to use. The return statement sends that result back to the caller. Once Python reaches a return statement, the function stops and the value travels back to wherever the function was called from.

python
def add(a, b):
    """Return the sum of two numbers."""
    return a + b

result = add(3, 7)
print(result)   # Output: 10

# The returned value can be used directly in expressions
print(add(10, 5) * 2)   # Output: 30
Common Mistake

Printing inside a function and returning a value are not the same thing. A function that calls print() displays output to the terminal but gives back None. If you need the result for further calculation, use return — not print().

Understanding variable scope

Variables created inside a function are local — they only exist within that function's execution. When the function finishes, those variables are discarded. Variables created outside any function are global and readable from anywhere in the program, but modifying them from inside a function requires the global keyword, which should be used sparingly.

python
def calculate():
    result = 42   # local variable — only lives inside this function
    return result

calculate()

# This would raise a NameError — result does not exist outside
# print(result)   # NameError: name 'result' is not defined

# Global variable example
message = "I am global"

def show_message():
    print(message)   # can read a global variable

show_message()   # Output: I am global
Anatomy of a Python function — each part of the definition labelled, with the return flow shown.

How to Create a Reusable Function in Python

Follow these steps each time you write a new Python function. Applying them consistently produces functions that are easy to read, test, and reuse across your codebase.

  1. Write the def keyword and choose a function name

    Type def followed by a descriptive name in lowercase with underscores. Add parentheses and a colon at the end of the line. Example: def calculate_total():

  2. Add a docstring to describe what the function does

    On the first line inside the function body, write a short string in triple quotes explaining the function's purpose. Example: """Return the total price after applying a discount.""" This step is optional but strongly recommended.

  3. Define parameters inside the parentheses

    If the function needs input values, list parameter names separated by commas inside the parentheses. Assign default values with = for any optional parameters. Example: def calculate_total(price, tax_rate=0.08):

  4. Write the function body with proper indentation

    Every line of code inside the function must be indented by the same amount — four spaces is the Python standard. The indentation is how Python knows the code belongs to the function, not the surrounding program.

  5. Use a return statement to send back a result

    If the function should produce a value, end the body with return followed by the value or expression to return. Functions that only perform an action (like printing) do not need a return statement and will automatically return None.

  6. Call the function by name and pass arguments

    Outside the function definition, type the function name followed by parentheses and pass any required argument values. Assign the return value to a variable if you need to use it later. Example: total = calculate_total(49.99)

"A function should do one thing, and do it well." — Unix Design Philosophy

Python Learning Summary Points

  1. A Python function is defined with the def keyword, a name, parentheses, and a colon. The indented block below is the function body and only runs when the function is called.
  2. Parameters are variables listed in the function definition that receive values when the function is called. Providing a default value makes a parameter optional. The return statement sends a result back to the caller — without it, the function returns None.
  3. Variables created inside a function are local and disappear when the function finishes. Writing functions that accept inputs through parameters and deliver outputs through return values — rather than reading and writing global variables — keeps programs predictable and easy to test.

Functions are the first major building block that separates code you type once from code that works everywhere. With parameters and return values, a single function can handle an entire category of problems rather than just one specific case. Practice by taking any repeated block in your own scripts and wrapping it in a function — the habit will pay dividends across every program you write from here on.

check your understanding question 1 of 4

Frequently Asked Questions

A function in Python is a named, reusable block of code that performs a specific task. You define it once using the def keyword and call it as many times as needed throughout your program.

You define a function in Python using the def keyword, followed by the function name, a pair of parentheses, and a colon. The indented code block below it becomes the function body. For example: def greet(): print('Hello')

A parameter is a variable listed inside the parentheses of a function definition. It acts as a placeholder for the value that will be passed in when the function is called. The value passed in is called an argument.

The return statement sends a value back to the part of the program that called the function. Once Python reaches a return statement, the function stops executing and the specified value is passed back to the caller.

If a function does not include a return statement, Python automatically returns the special value None. This is appropriate for functions that perform an action (like printing) but do not need to produce a result.

A parameter is the variable name defined in the function signature. An argument is the actual value you pass when calling the function. The two terms are often used interchangeably in casual conversation, but they refer to different moments in the function lifecycle.

Variable scope determines where in a program a variable can be accessed. Variables created inside a function are local in scope, meaning they only exist within that function. Variables created outside any function are global and can be read from anywhere in the program.

Yes. You can assign a default value to a parameter by using an equals sign in the function definition — for example def greet(name='World'). If the caller does not supply that argument, the function uses the default value automatically.

Functions eliminate repetition, making programs shorter and easier to maintain. When the same logic appears in one function, you only need to fix or update it in one place. Copying and pasting code means any future change must be applied everywhere the code was pasted, which leads to errors.

Python does not enforce a strict limit on the number of parameters a function can have. However, functions with many parameters become harder to read and call correctly. Keeping functions focused on a single task naturally limits parameter count.