Learn How to Write a Function in Python: Absolute Beginners Tutorial

Functions are the single most important building block you will learn in Python. Once you can write a function, you can stop copying and pasting the same code over and over — and start writing programs that are organized, readable, and easy to change.

This tutorial starts at the very beginning: what a function is, what every part of the syntax means, and how to avoid the mistakes that trip up almost every new Python programmer. Each section builds on the last, and there are interactive exercises throughout so you can test what you are learning as you go.

What Is a Function and Why Do You Need One

A function is a named block of code that you define once and can run as many times as you want. Instead of writing the same logic in three different places, you write it once in a function and call that function wherever you need it.

Think of a function like a recipe. You write the instructions once. Every time you want to make the dish, you follow that same recipe rather than rewriting the steps from scratch. The ingredients you hand to the recipe are the inputs, and the finished dish is the output.

Python already includes hundreds of built-in functions you have probably already used. print(), len(), and range() are all functions. When you write your own functions, you are doing exactly what the Python developers did when they wrote those built-ins — packaging code so it can be called by name.

Note

Writing your own functions is called defining a function. Running a function is called calling or invoking it. These two actions are always separate: you must define before you call.

The Anatomy of a Python Function

Every Python function follows the same structure. Once you recognise each part, writing functions becomes mechanical.

python
def greet(name):
    """Return a greeting string for the given name."""
    message = "Hello, " + name + "!"
    return message

Here is what each part does:

What it is
A reserved Python keyword that tells the interpreter you are about to define a function.
Common mistake
Writing Def or DEF instead of lowercase def. Python is case-sensitive.
What it is
The name you choose for your function. You use this name to call the function later.
Naming rules
Use lowercase letters and underscores. Names must start with a letter or underscore, not a number. Descriptive names like calculate_tax are better than vague names like do_thing.
What it is
The parentheses hold the parameter names — the inputs the function expects. A function with no inputs still needs empty parentheses: def say_hi():
Common mistake
Forgetting the parentheses entirely. def greet: is a SyntaxError.
What it is
The colon ends the def line and tells Python that an indented block is coming next.
Common mistake
Forgetting the colon. Python immediately raises a SyntaxError if it is missing. This is the number one mistake beginners make.
What it is
All the code that belongs to the function must be indented by the same amount — conventionally four spaces. Python uses indentation to determine what is inside the function.
Common mistake
Mixing tabs and spaces, or indenting inconsistently. Use four spaces consistently throughout your file.
What it is
A string on the first line of the body, written in triple quotes, that describes what the function does. It is optional but strongly recommended.
Why it matters
Running help(greet) in the Python shell displays your docstring. IDEs also show it automatically when you hover over a function name.
Pro Tip

Defining a function does not run any of its code. Nothing happens until you call the function. You can define a function at the top of your file and call it anywhere below the definition.

code builder click a token to place it

Build the correct def line for a function named add_numbers that takes two parameters, a and b:

your code will appear here...
|: add_numbers b def a, return ( ) :
Why: A def line follows the pattern def name(params):. The def keyword comes first, then the function name, then parentheses containing the comma-separated parameters, and finally a colon. return belongs inside the function body — not on the def line itself.

Parameters, Arguments, and Default Values

Parameters and arguments are two words that describe the same idea from different angles. A parameter is the variable name in the function definition. An argument is the value you pass in when you call the function.

python
# name is the parameter
def greet(name):
    print("Hello, " + name)

# "Kandi" is the argument
greet("Kandi")

A function can take multiple parameters separated by commas, or no parameters at all.

python
# Two parameters
def add(a, b):
    return a + b

# No parameters
def say_hello():
    print("Hello!")

Default Parameter Values

You can give a parameter a default value so the caller does not have to pass it. Write the default using an equals sign in the parameter list.

python
def greet(name="stranger"):
    print("Hello, " + name + "!")

greet()           # prints: Hello, stranger!
greet("Kandi")    # prints: Hello, Kandi!
Watch Out

Parameters with default values must always come after parameters without defaults. Writing def greet(name="stranger", title): raises a SyntaxError. The correct order is def greet(title, name="stranger"):.

spot the bug click the line that contains the bug

This function is supposed to print a personalised greeting. One line contains a bug. Click it, then hit check.

1 def greet(name, greeting="Hello"):
2 """Print a greeting for the given name."""
3 message = greeting + ", " + name + "!"
4 print(massage)
The fix: Change print(massage) to print(message). The variable is named message but was misspelled as massage. Python would raise a NameError: name 'massage' is not defined at runtime because no variable with that name exists in scope.

The return Statement

The return statement sends a value out of the function back to the code that called it. Without return, the function still runs, but calling it produces None.

python
def square(n):
    return n * n

result = square(5)
print(result)    # 25

The returned value can be stored in a variable, passed directly to another function, or used inside an expression.

python
def square(n):
    return n * n

# Stored in a variable
x = square(4)

# Passed to another function
print(square(3))

# Used in an expression
total = square(2) + square(3)
print(total)    # 13

Once Python executes a return statement, the function stops immediately. Any code written after return in the same function body will not run.

python
def check_positive(n):
    if n > 0:
        return True
    return False    # only reached if n is not positive

print(check_positive(5))    # True
print(check_positive(-3))   # False
How data enters a function through parameters and exits through the return statement.

Variable Scope Inside Functions

A variable created inside a function is local to that function. It only exists while the function is running, and it cannot be accessed from outside.

python
def calculate():
    result = 42    # local variable
    return result

print(calculate())    # 42
print(result)         # NameError: name 'result' is not defined

Variables defined outside all functions are in the global scope. Functions can read global variables, but to modify one you must use the global keyword. For beginners, the cleanest approach is to pass values in through parameters and get results back through return, avoiding global modification altogether.

Note

Each function call creates its own local scope. Two separate calls to the same function each get their own independent copies of local variables. They do not share state unless you return and pass values explicitly.

check your understanding question 1 of 4

correct answers

How to Write a Function in Python

Follow these four steps each time you write a new function. The steps apply whether you are writing a one-liner or a complex multi-parameter function.

  1. Write the def line

    Start with def, followed by the function name, parentheses containing any parameters, and a colon. For example: def greet(): or def add(a, b):. The colon is required — leaving it out raises a SyntaxError immediately.

  2. Indent the function body

    On the next line, indent by four spaces and write the first statement of the function body. Every line that belongs to the function must be at this indentation level. The body is what runs each time the function is called.

    python
    def greet():
        print("Hello!")    # four spaces of indentation
  3. Add a return statement if needed

    If the function should produce a value, add return followed by the value or expression on the last meaningful line. If the function only performs an action (like printing), you can omit return entirely — Python will return None automatically.

    python
    def add(a, b):
        return a + b
  4. Call the function

    After the function is defined, call it by writing its name followed by parentheses. Pass the required arguments inside the parentheses. You can call the function as many times as you need, with different arguments each time.

    python
    greet()           # Hello!
    result = add(3, 7)
    print(result)     # 10

Python Learning Summary Points

# key takeaways

  • A function is defined with the def keyword, a name, parentheses, and a colon. The body must be indented.
  • Calling a function and defining one are separate actions. Nothing in the body runs until you call the function.
  • Parameters are variable names in the definition. Arguments are the values you pass when calling.
  • Default parameter values allow arguments to be optional. Parameters with defaults must come after those without.
  • The return statement sends a value back to the caller and immediately stops the function.
  • Variables defined inside a function are local and cannot be accessed from outside the function.
  • A docstring — a triple-quoted string on the first line of the body — documents what the function does.

Frequently Asked Questions

A function in Python is a named, reusable block of code defined with the def keyword. It runs only when called, can accept input values through parameters, and can return a result using the return statement.

You define a function using the def keyword followed by the function name, parentheses, and a colon. The function body is written on the indented lines below. For example: def greet(): print("Hello")

A parameter is the variable name listed inside the parentheses in the function definition. An argument is the actual value you pass to the function when you call it. The parameter receives the argument's value when the function runs.

The return statement ends the function and sends a value back to the code that called it. Without a return statement, Python functions implicitly return None. The returned value can be stored in a variable or used directly in an expression.

Python will raise a SyntaxError immediately. The colon is required — it signals to Python that a new indented block is starting. This is one of the most common mistakes beginners make when writing their first functions.

Yes. A function with no parameters still requires empty parentheses in both the definition and the call. For example: def say_hello(): print("Hello") is valid. Calling it as say_hello() runs the function.

A default parameter value lets you define a fallback value for a parameter. If the caller does not pass an argument for that parameter, the default is used. You set it in the definition like this: def greet(name="stranger"). Calling greet() uses "stranger", while greet("Kandi") uses "Kandi".

Variables defined inside a function are local in scope, meaning they only exist while the function is running and cannot be accessed from outside. Variables defined outside the function are in the global scope and can be read inside a function, but modifying them requires the global keyword.

You call a function by writing its name followed by parentheses. If the function expects arguments, you pass them inside the parentheses. For example, if you defined def add(a, b): return a + b, you call it with add(3, 4) to get back 7.

A docstring is a string placed on the first line of a function body, enclosed in triple quotes, that describes what the function does. Beginners should use them from the start as a good habit. Python tools and IDEs can display docstrings automatically to help developers understand code.