Basics of Python Functions: Make Your Code Reusable

Python functions make your code more readable and reusable. A function is a reusable block of code that executes a specific operation or returns a result.

Once you define a function you can call it over and over in your code without having to rewrite that code again (avoid code duplication).

By the end of this tutorial, you will know how to create a function in Python and how to call it.

What are Python Functions?

The concept of function in Python is the same as in many other programming languages.

Functions allow you to organize code in modular blocks and make code reusable. The more your Python code grows the more difficult it can get to manage it if you don't use functions.

Below you can see the full syntax of a function:

def function_name(parameters):
    """docstring"""
    function_body

The components used to define a Python function are:

  • header: this is made of the def keyword, used to start the definition of the function, the function name, parameters enclosed within parentheses, and the colon symbol. Parameters are optional, a function can also have no parameters. Also, a function can have any number of parameters.
  • docstring: provides documentation about the function.
  • body: this is a sequence of Python statements and it can end with an optional return statement if the function returns a value.

Let’s see an example of a function that accepts a single parameter and prints a message that depends on the value passed when calling the function.

def say_hello(name):
    print("Hello " + name)

The name of the function is say_hello() and it accepts one parameter called name.

The function executes a single print statement that concatenates the word “Hello” with the value of the parameter passed to the function.

You call a Python function using the name of the function followed by parentheses. Within parentheses, you provide any values to be passed to the function (these are called function arguments).

say_hello("Codefather")
# Hello Codefather

How Does a Python Function Work?

We have seen how to define a function and how to call it.

The following diagram shows how a function works in the execution flow of a program.

How does a Python function work?

The Python program is executed line by line until the call to the function is encountered, in this case, say_hello().

At that point, the execution of the main Python program jumps to the function and goes through all the lines of code in the function until the function ends or a return statement is found.

Then the execution of the program continues from the next line after the function call and it continues until the last line of the main program.

How to Define a Function in Python Using the def Keyword

In the previous example, you created a function that contains a single line of code.

A function with multiple lines of code can be defined but every line in the function body must have the same indentation. If the indentation of lines within a function is not the same the Python interpreter raises a syntax error.

Let’s update the previous function to print today’s date using the datetime module.

from datetime import date

def say_hello(name):
    today = str(date.today())
    message = "Hello " + name + ". Today is " + today
    print(message)

The first line of the function gets today’s date and converts it into a string. The second line of the functions shows how to concatenate strings in Python (in this case how to concatenate the date string with “Hello” message).

The function prints the following message when you call it (see the code on the third line of the function).

Hello Codefather. Today is 2021-07-31

If you forget to convert today’s date into a string you will get the following TypeError exception:

Traceback (most recent call last):
  File "functions.py", line 9, in <module>
    say_hello("Codefather")
  File "functions.py", line 5, in say_hello
    message = "Hello " + name + ". Today is " + today
TypeError: can only concatenate str (not "datetime.date") to str

Notice that the three lines in our function follow the same indentation.

Let’s modify one of the lines in the function to use an incorrect indentation.

def say_hello(name):
    today = str(date.today())
message = "Hello " + name + ". Today is " + today
    print(message)

And see what happens…

  File "functions.py", line 6
    print(message)
    ^
IndentationError: unexpected indent
When the indentation of one or more lines in a function is incorrect, the Python interpreter raises an IndentationError exception.

What is the return Statement in a Python Function?

In the function, we have seen so far the function gets called and prints a message.

The most common approach when using a function is for the function to return one or more values to the caller (the line of code where the function is called).

Here is what I mean…

I want to create a program that calculates the sum of two numbers. Without using a function I could write the following code:

number1 = 10
number2 = 15
result = number1 + number2
print("The sum of the two numbers is " + str(result))

What if we want to write a function that we can reuse in the future when we want to calculate the sum of two numbers?

We can add a return statement to it.

def calculate_sum(a, b):
    result = a + b
    return result

What does the return statement in Python do?

As you can see, in the function above we:

  • take two parameters a and b.
  • calculate the sum of the two parameters.
  • use the return keyword to return the result of the sum.

This allows us to use the return value in the main program.

number1 = 10
number2 = 15
print("The sum of the two numbers is " + str(calculate_sum(number1, number2)))

Can you see how this time in the print statement we call the function?

We can do that because the function returns the sum using the return statement.

You have reached the end of this tutorial. To recap, a function is a block of code you can reuse by calling it in your Python programs.

The following tutorials will help you build your knowledge of Python functions:

If you have any questions feel free to email me at hello@codefather.tech.

And to help you get started with Python I created a tutorial on how to start programming in Python.

Leave a Comment