Modules and functions in Python

Coding with Python

🕑 This lesson will take about 30 minutes

In this lesson, you will learn about modules and functions that are available for you to use in Python.

Functions

A function is a block of organised, reusable code that is designed to perform a specific task. Functions are given unique names that you can call them by when you wish to use them throughout your code. Functions provide a way to group code into reusable blocks of code, making code more modular, readable, and easier to understand, test and debug. Functions help in breaking down a program into smaller, manageable parts, promoting code reuse and maintainability.

Functions can perform a specific task (such as displaying a message) or return a value that can be used however you like (eg. store the returned value in a variable for later use, display it, use it in another operation, etc).

The Python language has many existing functions you can use - you have already used some of these functions such as the print() function, the input() function, and the str() function. But you can also make your own functions.

To use an existing function, you first type in the function’s name followed by a set of parentheses - values for parameters that the function might need can be specified within these parentheses. A parameter is any information that a function needs to solve a problem. Parameters are defined when the function is created and values, known as arguments, are provided for these parameters when the function is called.

Earlier on in these lessons, we looked at working with numbers and math in Python. We looked at using exponential calculations, for example, 5 raised to the power of 3 power could be written as 5**3 in Python code (which gives the answer of 125). However, there is an easier way to do this using an existing function. This function is called the pow() function. To use this function, firstly write it’s name which is pow and then any parameters that the pow function needs between parentheses – the parameters are the base and the exponent, each separated by a comma.

In the example code below, the pow() function is called and the values of 5 and 3 are provided for the two parameters (base and exponent). These real values provided for the parameters when the function is called are known as the arguments for the function.

Another example of a useful function is the round() function which is used to round numbers up. In the example below, the value of 18.7 will be rounded up to 19.

Modules

Many functions are readily available to use in Python code (such the pow or round functions) just by calling their name. However, many existing Python functions require you to import the module they belong to first, before you can use them in your program. Modules are a collection of different related functions. Common modules in Python include math (which contains a collection of math-related functions), datetime (which contains a collection of date and time-related functions), random (which contains functions for generating random numbers), and several more.

Let’s take a look at some common functions from the math module in Python. To use these functions, you’ll first need to import the math module into your program using the import statement. This should usually be written at the top of your code. When using these math functions, you specify both the module name and function name with a period in between, for example, math.sqrt(25) would be written to return the square root of 25.

The datetime module is another module in Python that contains a collection of functions you can use. These functions allow you to work with dates and time. Check out the example code below which shows how to get the current date and/or time, create dates, and format dates using functions from the datetime module.

Creating your own functions

You can also create your own functions in Python by defining a function (using the def keyword), giving the function a specific name, and specifying what the function does.

Try it out:

In the example above, a new function has been defined. The function’s name is myFunction and all it does is display a message saying “Hello, this is my function”. Note the use of indentation for code that belongs to the function. Indentation is very important for structuring code in Python and telling Python which code belongs to what structure (Python doesn't use curly brackets to contain code like other languages might). Any instructions that belong to a function must be indented below the def line of code. Any lines of code that follow, that aren’t indented, will not belong to the function. To use the function in your program, you just need to call it by its name (and include the parentheses after the function name).

Specifying parameters and arguments

When defining a new function, you can optionally specify one or more parameters that you want the function to use whenever it is called. These parameters are given names and are identified between the parentheses after the function’s name when it is created. Each parameter is separated by a comma. You can then use those parameters in the function's code. When the function is called, you specify the real values (called arguments) that will be passed into the function and represented by the parameter names in the function.

Check out the example code below. In this example, a function called calculate_area() has been created which will calculate the area of a rectangle. The function has two parameters - length and width. It then uses the print() function to output the length multiplied by the width. When the function is called, real values are provided for the length and width parameters. In this example, 10 has been provided for length and 5 has been provided for width. These values provided for the parameters are called arguments.

Returning values

One of the issues with the code in the example above is that the calculate_area() function uses the print() function to output/display the results of the calculation. This makes the function not very reusable. What if you wanted to calculate the area of a shape without immediately displaying the result? What if you wanted to store the result in a variable to use later on? What if you wanted to use the result in another operation or with another function (eg. to add the result to a total, or to round the result up or down)?

What we can do instead, is use the return statement to return the result (the calculated area) to the code that is calling the function. Then that other code can decide what to do with the result (eg. whether to store it in a variable, display it, etc). Returning a value just means to pass a value from the function back to the code that has called it.

Check out the example below. Instead of using the print() function inside the calculate_area() functions’ definition, the calculated area result is returned instead so the programmer can decide what to do with it. In this example, when the function returns a value, that value is stored in a variable and later displayed to the user.

Earlier in this lesson, we looked at modules that exist in the Python language. If you’re creating a collection of your own related functions, you might want to create your own module. This is something we will look at a little later in the course.

What is the difference between a parameter and an argument?

An argument is the value that is passed into the function (as input) when the function is called. However, the term parameter refers to the names of these values that are used within the function to refer to the values. Parameters represent the arguments (real values) that are sent to the function when the function is called. Parameters are like temporary variables used inside a function. So, in the example above, when the values 10 and 5 are provided for the parameters length and width, we would say that the values 10 and 5 are the arguments provided for the parameters length and width.

Review questions

  1. What is the difference between a function and a module in Python?

  2. Find five useful functions that already exist in Python (other than the examples used in this lesson).

  3. How do parameters and return statements improve the readability and reusability of code?

Next lesson: Working with strings