Skip to content

Functions in Python

Understanding and Using Functions in Python for Data Science Cover Image

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:

Don’t Repeat Yourself

Python functions allow us to better follow the programming DRY principle. The principle is an acronym for Don’t Repeat Yourself. Whenever you find yourself repeating lines of code, you may want to consider turning this into a function.

Readability

Python functions allow us to build more readable code. By being able to clear define the action that our function provides, we’re able to readily communicate to a reader what our code is doing.

Abstraction

Our readers don’t need to understand the underlying mechanics of how our code works. Think, for example, of calculating a standard deviation. Your readers don’t need to know the ins and outs, just how to call the function!

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:

print('Hello, World!')

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:

  1. Functions are defined using the def keyword
  2. The function name is a single string that should be descriptive and doesn’t contain spaces
  3. Parentheses follow the function name and can either contain nothing or contain parameters, as you’ll learn about soon
  4. The first line ends with a colon
  5. 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!

greet()

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.

What is the difference between a Python function parameter and an argument?

While these terms are often used interchangeably, they do refer to different things.

A function parameter is the variable listed in the function definition (i.e., the one used in the parentheses in the first line of the function). Meanwhile, a function argument refers to the value that is passed into the function, when the function is called.

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?

greet()

Solution

TypeError: greet() missing 1 required positional argument: 'name'

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 + '!')

While '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:

  1. We defined our function, similar to our previous function, using the def keyword
  2. We gave the function a descriptive name
  3. We assigned two parameters, allowing us to pass in two values
  4. We assign the variable of sum to the value of adding our two parameters together
  5. We use the return keyword to return the variable sum

Let’s try running this! Copy the function definition above and then call the function with two different numbers. In order to do this, write code similar to what you see below:

def add_nums(x, y):
    sum = x + y
    return sum

sums = add_nums(3, 4)
print(sums)

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:

  1. The first line provides an overview of what the function is hoping to accomplish
  2. The second second provides an overview of the arguments (args) being passed into the function, including their expected data types
  3. 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 add_nums() function.

Let’s see how we can call the help() function on our function to return useful information about it.

help(add_nums)

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.

Seeing Docstrings in a Python Function
How docstrings can help you understand functions in an IDE

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:

  1. The function should be named in a descriptive manner
  2. The function should have two parameters: (1) the bill amount and (2) the tip percentage (as a floating point value)
  3. 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 AmountTip PercentageTip Amount (Solution)
10.9915%1.6485
53.4523%12.293500000000002
2312%2.76
Expected solutions to your function test

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!

Sample solution:

def calculate_tip(bill_amt, tip_prct):
    """Calculate a tip amount of a provided bill and tip percentage.

    Args:
        bill_amt (int | float): the value of your bill
        tip_prct (float): the percentage of your tip, represented as float
    """

    return bill_amt * tip_prct / 100

Conclusion

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.

Additional Resources

To learn more about Python functions, check out these additional helpful resources:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

32 thoughts on “Functions in Python”

  1. Pingback: Pivot Tables in Pandas with Python for Python and Pandas • datagy

  2. Pingback: Python 3: Installation and Setup • datagy

  3. Pingback: Combine Data in Pandas with merge, join, and concat • datagy

  4. I am lost. I can’t get it to add, the screen just goes blank. I even tried copy/paste you solution for the tip_calc and still blank. Where do I put the values (such as 10.99 & 15%) ???

      1. I am running directly in your code editor. I don’t know really how to describe it. I can run the statements fine, but when I try to do the process, and hit run, it’s a blank screen (no error). For example, if I type this:
        def add_nums(x, y):
        sum = x + y
        return sum
        add_nums(1, 2)

        all I get is a blank editor with the “powered by trinket” in the editor, when I should expect to get the sum of 1+2 = 3. I am having issues ‘calling’ the result

  5. ok, so I feel dumb now, but kinda elated. I googled forever and read articles……I was forgetting to type print on my last line, therefore nothing was actually displaying. crisis averted. ha

  6. def achivement(day):
    “””Tell about your achivements”””
    message = f”Day {day} done!”

    print(message)

    achivement(2)

  7. Hi Nik,
    def add_nums(x, y):
    sum = x + y
    return sum

    add_nums(3+2)

    Why is not calling the function. Where to put print function in this

    1. Great question! I have fixed the code in the article. The original was unclear in showing you how to use the function and how to print it. That should be fixed now :).

Leave a Reply

Your email address will not be published. Required fields are marked *