Basics of Python Functions: Make Your Code Reusable

Claudio Sabato
5 min readJul 31, 2021

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 simply call it over and over in your code without having to rewrite that code again (avoid code duplication).

We will start by looking at how to create a function and then section after section we will keep building on the concepts you will learn.

By the end of this tutorial, you will know how to define 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.

A function allows you to organize code in modular blocks and it makes 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 def keyword, used to start the definition of the function, function name, parameters enclosed within parentheses, and the colon symbol. Parameters are optional, this means that 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.

--

--

Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python/Bash programming, Linux Systems Administration and IT Systems Design.