Last modified: Aug 22, 2026

How to Write a Function in Python

Functions are the building blocks of any Python program. They let you reuse code, keep things organized, and make your scripts easier to read. If you are starting with Python, mastering functions is a key step. This guide will show you how to write a function in Python from scratch, with simple examples and useful tips.

Why Use Functions?

Writing the same code over and over is a waste of time. Functions help you avoid repetition. They also make debugging easier because you can test small parts of your code separately. When you write a function, you create a named block of code that runs only when you call it.

Think of a function like a recipe. You define the ingredients (inputs) and the steps (instructions). Once the recipe is ready, you can use it any time you want the same result. This is exactly how functions work in Python.

Basic Syntax of a Python Function

To write a function, you start with the def keyword. The word def stands for define. After that, you give the function a name, add parentheses, and end the line with a colon. The body of the function is indented.


# Simple function with no parameters
def greet():
    print("Hello, world!")

# Call the function
greet()

Hello, world!

Notice the indentation. Python uses spaces to know which lines belong to the function. You must be consistent with your indentation, usually four spaces. If you forget the colon or the indentation, you will get an error.

Adding Parameters to Your Function

Most functions need input to work with. You can pass data into a function using parameters. Parameters are placeholders inside the parentheses. When you call the function, you provide actual values called arguments.


# Function with one parameter
def greet_user(name):
    print(f"Hello, {name}!")

# Call with an argument
greet_user("Alice")

Hello, Alice!

You can also use multiple parameters. Just separate them with commas. This makes your function more flexible and powerful. For example, a function to add two numbers takes two parameters.


# Function with two parameters
def add_numbers(a, b):
    result = a + b
    print(result)

add_numbers(5, 3)

8

Returning Values from a Function

Printing is not the same as returning. When you want your function to give back a value for further use, you use the return statement. This is a critical concept. A function without a return statement returns None by default.


# Function that returns a value
def multiply(x, y):
    return x * y

# Store the result
product = multiply(4, 5)
print(product)

20

Using return allows you to use the result in other parts of your code. You can assign it to a variable, pass it to another function, or use it in a condition. This makes your functions much more useful.

Default Parameters and Keyword Arguments

Sometimes you want a function to work even if the caller does not provide all arguments. You can set default values for parameters. If the caller omits an argument, the default value is used.


# Function with a default parameter
def power(base, exponent=2):
    return base ** exponent

print(power(3))      # Uses default exponent 2
print(power(3, 3))   # Uses exponent 3

9
27

You can also call functions using keyword arguments. This means you specify the parameter name when you call the function. It makes your code clearer and helps avoid mistakes with argument order.


# Using keyword arguments
def describe_pet(animal, name):
    print(f"I have a {animal} named {name}.")

describe_pet(animal="dog", name="Rex")

I have a dog named Rex.

Scope and Lifetime of Variables

Variables inside a function are local. They exist only while the function runs. You cannot access them from outside. This is called scope. It keeps your code clean and prevents accidental changes to global variables.


def my_function():
    local_var = 10
    print(local_var)

my_function()
# print(local_var)  # This would cause an error

10

If you need to modify a global variable inside a function, you must use the global keyword. However, this is generally not recommended. It makes your code harder to understand. Try to keep functions self-contained.

Docstrings: Documenting Your Function

Good code is easy to read. Adding a docstring is a best practice. A docstring is a string right after the function definition. It explains what the function does. You can view it with the help() function.


def square(num):
    """Return the square of a number."""
    return num ** 2

help(square)

Help on function square in module __main__:

square(num)
    Return the square of a number.

Docstrings are not just comments. They are part of the function's official documentation. Many tools use them to generate documentation automatically. Always write a clear docstring for your functions.

Common Mistakes and How to Avoid Them

Beginners often make a few mistakes. One is forgetting the colon after the function definition. Another is mixing tabs and spaces for indentation. Always use spaces. Also, remember to call the function with parentheses, even if there are no arguments.

Another common issue is naming conflicts. Avoid using built-in names like list or dict for your functions. This can cause unexpected behavior. Use descriptive names that tell what the function does.

Finally, do not forget to return a value if you need one. If you only print inside the function, you cannot use the result later. This is a frequent source of confusion.

Best Practices for Writing Functions

Keep your functions small and focused. A function should do one thing well. If it is doing too much, consider breaking it into smaller functions. This makes testing easier and improves readability.

Use descriptive names. A function called calculate_average is much better than calc. Also, use verbs for function names because they perform actions. This helps anyone reading your code understand its purpose instantly.

Always test your functions with different inputs. This ensures they work correctly in all cases. You can write simple test calls in your script or use Python's built-in testing tools.

Conclusion

Learning how to write a function in Python is essential for any programmer. It helps you write cleaner, more efficient, and reusable code. Start with simple functions, then add parameters, return values, and default arguments as you get comfortable. Remember to use docstrings and follow best practices. With practice, you will find functions become second nature, and your code will improve dramatically.