Articles
Back to articles list
- 8 minutes read

How To Define a Function in Python

If you have written any code in Python, you have already used functions. Print(), max(), and sum() are all built-in Python functions. However, did you know that you can also define your own functions? Let’s go through how to define and call a function in Python.

What Is a Function in Python?

In programming, a function is a block of code that performs a certain task or a group of related tasks.

If you notice that you often use the same block of code over and over again, consider writing a corresponding function. Then, the next time you need this piece of code, you can simply call the function.

User-defined functions bring several important benefits:

  • Functions are convenient when you need to regularly accomplish the same task. After defining a function, you simply call it instead of typing or copy-pasting the same code snippet over and over again. Moreover, if you decide to change a block of code, you only need to change it where you define the function. This change will be applied anywhere the function is called.
  • By defining and using functions, you can break complex programs into smaller steps. Each step can be a separate function solving a specific task.
  • Finally, with user-defined functions, your code is usually easier to follow. You can clearly see which task is accomplished with each code block. This is especially true when functions are defined following the best practices discussed later.

Are you excited? Okay, let’s define a couple of functions together.

Defining a Function in Python: Syntax and Examples

The syntax for defining a function in Python is as follows:

def function_name(arguments):
    block of code

And here is a description of the syntax:

  • We start with the def keyword to inform Python that a new function is being defined.
  • Then, we give our function a meaningful name.
  • Next, in parentheses, we list the arguments or parameters that the function needs to perform a task. You can include as many parameters as you want. If you define a function without parameters, you can also leave the parentheses empty.
  • The colon symbol “:” denotes the end of the function’s header and a transition to the function’s body.
  • After the indentation, we write the code block needed to perform the task at hand.
  • When done with the code block, we leave an empty line to mark the end of the function definition.

Now that you know the syntax, I recommend practicing your function-defining skills. A great way to do this is with our Python Basics. Part 1 course.

Functions With One Parameter

Let’s start with a simple function that takes a name as the input and prints out an introduction line. Here’s how to define this function:

def introduction(name):
    """Introduces a person given their name"""
    print('Hello! My name is', name)

This function, called introduction, has one argument, name. The body of this function includes only one line, which prints out the message, including the name. We have also added a comment explaining the purpose of our function.

Now, let’s call it and check the output:

introduction(‘Kateryna’)

Output

Hello! My name is Kateryna

We simply pass the name to our function (note the quotation marks since the name is a string) and get the introductory message as the output.

Even a small function with only one line of code saves us time if it’s used regularly. So, imagine the benefits with longer code blocks!

Functions Without Parameters

In some cases, you may want to define functions without any arguments. For example, let’s write a function that will print out an error message about an incorrect password:

def error_message_password():
    """Prints out an error message about the incorrect password"""
    print('Sorry. We couldn’t log you in. The password you entered didn’t match our records.')

This function doesn’t need any parameters. So, we define it, leaving the parentheses empty. When calling this function, you simply write its name followed with empty parentheses:

error_message_password()

Output

Sorry. We couldn’t log you in. The password you entered didn’t match our records.

Functions With Multiple Parameters

Now let’s define a more complex function with multiple parameters. This time, we want to create a function that will calculate a person’s age in years based on their birth date (birth year, birth month, and birth day). The function is as follows:

from datetime import date
def get_age(birth_year, birth_month, birth_day):
    """Calculates age (in years) based on birth year, birth month, and birth day."""
    birth_date = date(birth_year, birth_month, birth_day)
    age = date.today() - birth_date
    age_years = age.days / 365.2425
    return age_years

We start by importing the date class of the datetime module to work easily with dates. You can learn how to handle date and time data in Python with our Python Basics. Part 3 course.

Now, we are ready to define our get_age function. Note that this function requires three arguments: birth_year, birth_month, birth_day. In the body of the get_age function, we first define the birth_date based on the provided information.

Then, we calculate the age in days by subtracting the date of birth from today’s date. Finally, we calculate the age in years by dividing the age in days by 365.2425, the average number of days in one year.

Note the return statement at the end of the function definition. In our previous examples, we were using the print() function that allowed us to see the output of each function. But in most cases, you just need the function to return a certain value, not necessarily print it out.

That’s when the return statement comes into play. Use the return keyword to specify the return value, which can be just about any Python object (e.g., integer, string, list, tuple, dictionary, set, etc.).

Now, let’s call our get_age() function with multiple arguments. We have two options with regards to passing the arguments:

  • Positional arguments. This involves passing the arguments in the order that corresponds with parameters in the function definition:
    get_age(1987, 9, 2)
    

    Output

    33.57221571969308
    
  • Keyword arguments. This involves passing the arguments in an arbitrary order and specifying each parameter by name:
  • get_age(birth_day=2, birth_month=9, birth_year=1987)

    Output

    33.57221571969308
    

With keyword arguments, you don’t need to be attentive to the argument order, but you need to type the exact names of all of the parameters.

Also, note that no matter which option you choose, the number of arguments must match with the number of parameters in the function definition.

In the output above, you can see that the get_age() function returns the age in years as it was requested with the return statement. However, rather than just outputting this value, we may want to assign it to a variable. See how below:

kate_age = get_age(1987, 9, 2)
print(kate_age)

Output

33.57221571969308

Now, the kate_age variable holds the value returned by the get_age() function.

Functions That Return None

All Python functions return some value. If you don’t use the return statement explicitly, Python will supply an implicit return statement with None as the return value.

There might be cases in which you want your function to do some operations without returning any value. We could see this in our first two examples. We were printing out the results of the function without returning any value explicitly.

Now, let’s assign the result of our error_message_password() function to a variable and check the value of this variable:

error = error_message_password()
print(error)

Output

None

As you can see, the error variable stores the None value and not the error message, as you might expect. This is because, in our error_message_password() function, we were only printing out the error message without returning its value explicitly.

So, be attentive and always include the return statement if you want your function to return any value beyond None.

Best Practices For Writing Functions in Python

I’d like to conclude this guide by listing some helpful practices for defining functions in Python:

  • Use meaningful function names. Your functions should have meaningful names that reflect the tasks they are assigned to accomplish. This improves the code readability not only for other programmers working with your code but also for yourself when you return to your code after some time. Also, make sure to follow the Python conventions for function names: use only lower case, and separate words with an underscore.
  • Assign one task to one function. Ideally, one function should be responsible for one task. This supports clear code structure and improves readability.
  • Provide comments on the function task. Make sure to include a brief summary of what the function does right below the header. This comment is called a docstring and should be surrounded with triple-double quotes (“””).

Follow these practices so that your code looks clean and professional.

 

Time To Practice!

Congratulations, you now know how to define and call a function in Python! So, it’s time to consolidate this knowledge with real code challenges.

I recommend starting with the Python Basics. Part 1 course. It includes 95 interactive exercises covering conditional statements, “for” loops, “while” loops, and, of course, user-defined functions in Python.

If, after realizing the superpower of Python in 2021, you are eager to learn more, check out the whole Python Basics track. It includes two more courses covering lists, tuples, dictionaries, sets, date and time, and other useful topics. You can learn more about this track in our Python Basics overview article.

You are at the beginning of an exciting Python journey. To make this journey even more exciting and also effective, I want to share with you the 9 Best Online Resources to Start Learning Python.

Thanks for reading, and happy learning!

go to top