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.
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:
Are you excited? Okay, let’s define a couple of functions together.
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:
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.
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!
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.
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:
get_age(1987, 9, 2)Output
33.57221571969308
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.
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.
I’d like to conclude this guide by listing some helpful practices for defining functions in Python:
Follow these practices so that your code looks clean and professional.
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!