In this tutorial, you’ll learn more about functions in Python. You’ll learn what functions are, how to use functions, and how to develop your own functions. Python comes built-in with many different functions, many of which you’ve probably already used. A big part of becoming a Python developer is also being able to develop your own functions.
Let’s dive in!
What are Python Functions?
Python functions are groups of related statements that perform specific tasks. They allow us to repeat statements that are used multiple times in a modular, easy-to-read format. Because of this, they allow us to create modular code that provides helpful, descriptive chunks of working with our program.
What’s more, is that functions allow us easily bundle a set of instructions. This means that we’re able to create a specific function to carry out a specific task. Functions allow us to even pass inputs and generate outputs, meaning that we can use functions to carry out specific tasks for different pieces.
Why Write Functions in Python?
The section below provides a quick summary of why you may want to write functions in Python:
Now, you’ve probably already used functions! Think back to the first programming exercise you probably did: printing a ‘hello’ on your screen. If you wrote this in Python, it probably looked something like this:
Maybe without knowing that this was a function, you used a function. The code that makes up the
print() function is significantly longer than simply writing print.
This is where the concept of abstraction comes into play. Because we don’t need to (and, most likely, don’t want to) know the underlying code of the
print() function, it’s much easier and intuitive for us to simply call the function.
Imagine having to write out tens of tens of lines, each time you wanted to print something to your screen! Not only would this be tedious, but it would also be unclear to readers of your code to understand what’s really going on.
Now that you have a strong understanding of why you may want to use functions in Python, let’s take a look at creating functions!
Building Your First Python Function
In this section, you’ll learn just how easy it is to build functions in Python!
Python functions are defined using the
def keyword followed by the function name and parentheses:
def greet(): print('Hello!')
There’s a couple of things to note here:
- Functions are defined using the
- The function name is a single string that should be descriptive and doesn’t contain spaces
- Parentheses follow the function name and can either contain nothing or contain parameters, as you’ll learn about soon
- The first line ends with a colon
- The following lines are the body of the function. These lines are indented and contain the code you want the function to run.
Simply declaring a function doesn’t actually run the function. In order to run the function, we have to call it. The way that we can accomplish this is by writing the function name and opening and closing parentheses. Let’s give this a shot!
Now, try recreating the function in the box below! Make sure to define the function and then also call it. Once you’ve done this, click the run button and see if the function greets you!
In this example, we used a function that didn’t return anything and didn’t take any arguments. In the next section, you’ll learn how to use Python to create functions that take arguments.
Python Function That Take Arguments
In this section, you’ll learn how to extend the functionality of Python functions by passing in arguments. An argument is information that’s passed into a function that is then used within the function.
When we define a function to take arguments, we pass in a parameter in the function definition. We can then use this parameter in our function to either modify the behaviour of the function or to process it in different ways.
Following from the learnings of the previous section, functions allow us to modularize and repeat certain tasks. For example, the function we wrote in the previous section simply printed out a friendly greeting. We can extend the usefulness of our function by passing in a parameter.
Let’s build on our function to pass in a person’s name, allowing us to personalize our greeting.
def greet(name): print('Hello ' + name + '!')
Now, when we call this function, we can pass in a string. The string is then passed into the print statement, allowing us to customize the way the greeting is printed.
Let’s now practice calling this function. We’ll pass in the value of
'Nik' into the function call:
greet('Nik') # Returns: Hello Nik!
We can see that by passing a string that we were able to give our greeting a personal touch!
We were able to join together our strings using the
+ operator. When you add strings together, you’re really concatenating them. Because of this, we were able to join together the three separate strings.
Now, let’s take a look at the example below. What do you think will happen when we simply call the function, without passing in an argument?
We can see that Python expects an argument to be passed in. In fact, not passing in an argument causes the function call to fail and Python raises a
TypeError. The error code explicitly tells us that the function is missing an argument.
There may be times when you don’t want to pass in an argument, but you want the function to run with some default behaviour. In the next section, you’ll learn how to use default parameters in Python functions, to accomplish exactly this!
Working with Default Parameters in Python Functions
In the previous section, we saw that when Python expects an argument to be passed in and no argument is provided, that the function will generally fail. In many cases, you’ll want to provide some default value in order to keep your functions from failing.
Doing this is quite easy! Let’s take a look at passing in the string
'there' as the default argument:
def greet(name = 'there'): print('Hello ' + name + '!')
'there' doesn’t represent a name, it’s a nice, conversational way to handle no name being passed in. Now, when we call the function without passing in a value for the
name= parameter, Python will use the default value.
Let’s give this a shot!
greet() # Returns: Hello there!
Great! Similarly, when we do pass in an argument, Python will use the provided value.
In the next section, you’ll learn how to take your Python functions even further, by allowing them to return something.
Python Functions That Return Something
In the examples above, we simply used functions to print out a value. While this was useful for demonstrating how functions work, it’s not particularly useful in real-world applications. Generally, when working with functions in data science (or any other application), we want functions to process something.
Because we will want to be able to use the processed values, we need to program our functions to return something. What’s more, is that we can even assign this returned value (or values) to a variable (or variables).
We can return something from a function by using the
return keyword. The keyword terminates the function call and any code following running into this line of code isn’t run.
Let’s now create a new function that adds two numbers together and returns the sum of these values.
def add_nums(x, y): sum = x + y return sum
Let’s break down what we did here:
- We defined our function, similar to our previous function, using the
- We gave the function a descriptive name
- We assigned two parameters, allowing us to pass in two values
- We assign the variable of
sumto the value of adding our two parameters together
- We use the
returnkeyword to return the variable
Let’s try running this! Copy the function definition above and then call the function with two different numbers:
Cool, right? We can actually simplify our function a little bit! Since we only create the variable
sum in order to return it, we can actually pass the arithmetic expression directly into the
return keyword. Let’s see what this looks like:
def add_nums(x, y): return x + y
This is a lot easier to write and a lot cleaner to read. We don’t need to worry about what the variable
sum is used for and we don’t have to write an additional line of code.
Adding Docstrings to Python Functions
The more you write code, the more you’ll learn that writing clear and well-documented code is important. One important thing to add to your functions is what’s called a docstring. Docstrings are string literals that are inserted into the first line of a function and are used to provide information about the function.
Docstrings are generated using triple quotes and immediately follow the colon on a new, indented line. Let’s take the function above and add in a helpful docstring:
def add_nums(x, y): """Adds two numbers together and returns the sum. Args: x (int | float): the first number y (int | float): the second number Returns: int | float: the sum of the two numbers """ return x + y
You might be thinking, “wow, this is a lot to write for such a simple function”. While in this example that’s true, it’s a good habit to get into. Let’s break this docstring down a little bit:
- The first line provides an overview of what the function is hoping to accomplish
- The second second provides an overview of the arguments (
args) being passed into the function, including their expected data types
- The last section provides an overview of the value (or values) being returned by the function
What’s great about docstrings is that we can use the built-in
help() function to get information about the function. This is true for built-in functions as well as user-defined functions, such as our newly generated
Let’s see how we can call the
help() function on our function to return useful information about it.
This returns the following:
add_nums(x, y) Adds two numbers together and returns the sum. Args: x (int | float): the first number y (int | float): the second number Returns: int | float: the sum of the two numbers
This allows users of your code to easily understand (1) what your function does and (2) how your function works.
Similarly, if you’re using an integrated developed environment, such as Visual Studio Code, the docstrings tend to be available with the intellisense built into the software.
Now that you know everything you need to know to get started with Python functions, let’s take on an exercise to help solidify your learning!
Exercise: Building a Python Tip Calculator Function
In this section, you’ll be building a Python function that acts as a tip calculator. In building your function, make sure it meets the requirements listed below. You’ll also be provided with a few test values to test your function against. Finally, you’ll be able to see a sample solution to the problem.
Here are the requirements that your function should accommodate:
- The function should be named in a descriptive manner
- The function should have two parameters: (1) the bill amount and (2) the tip percentage (as a floating point value)
- The function should return the amount to be tipped
Use the code editor below to develop and test your function:
Use the table below to test your function:
|Bill Amount||Tip Percentage||Tip Amount (Solution)|
Toggle the section below to see a sample solution. It’s ok if your code isn’t exactly the same or your parameters are named differently!
In this tutorial, you learned everything you need to know to get started with Python functions. You learned why functions are useful and how to define functions. You then learned how to define functions that simply execute an action, how to modify behavior with arguments, and how to create functions that return values. Finally, you learned how to write descriptive docstrings to help explain your function to yourself and other users.
To learn more about Python functions, check out these additional helpful resources: