Save up to 80 % on our PHP e-learning courses. Only this week!
Get up to 40 % extra points for free! More info

# Lesson 12 - Importing modules and the math module in Python

In the previous lesson, Tuples, sets, and dictionaries in Python, we learned about multi-dimensional lists in Python. In today's tutorial, we're going to learn to use libraries. Mainly, the `math` library.

## Libraries

Libraries (or modules) provides us with useful data types, functions, and tools for making even better programs. They're made so we don't have to re-write something someone else has already written for us. If we make our programs using existing modules, the development process will be much more comfortable and quick.

We import libraries using the `import` command, at the beginning of our source file.

`import module_name`

Then, we call module functions as they were in the module's methods:

`module_name.function_name()`

We can also choose to only import certain functions:

`from module_name import function_name`

Then, the function would be globally accessible:

`function_name()`

We could even make everything from the module be accessible globally. However, be careful with this approach and use it only if you know exactly what you're doing:

`from module_name import *`

## `math`

First, let's introduce you to the Python math module - `math`. We have to import it in order to use it:

```#!/usr/bin/python3

import math```

The module provides 2 fundamental constants for us: `pi` and `e`. `pi`, as you all know, is the number Pi (`3.1415...`), and `e` is Euler's number, the base of the natural logarithm (`2.7182...`). I'm sure you'll get how to work with them. For completeness' sake, let's print these constants to the console:

``````{PYTHON}

import math

print("Pi: %f" % (math.pi))
print("e: %f" % (math.e))``````

The result:

```Console application
Pi: 3.141593
e: 2.718282```

As you can see, we can call everything from the `math` module.

## `math` module methods

Now, let's go over the methods that the math module provides.

### `ceil()`, `floor()`, and `random()`

All of these functions are related to rounding. `ceil()` always rounds upwards and `floor()` rounds downwards no matter what. If you just need ordinary rounding, use the global `round()` function which takes a decimal number as a parameter and returns the rounded number as a double data type in the way we learned in school (from `0.5` it rounds upwards, otherwise downwards). The `round()` function is from the standard set of functions and isn't dependent on the `math` module.

We'll certainly use `round()` very often. I've used the other functions for things such as determining the number of pages in a guestbook. If we had `33` comments and we only printed `10` comments per page, these comments would take up `3.3` pages. The result must be rounded up since we would actually need `4` pages.

``````{PYTHON}

import math

print(round(3.1))
print(round(3.6))
print(math.ceil(3.1))
print(math.floor(3.6))``````

The output:

```Console application
3
4
4
3```

### `fabs()` and `abs()`

The `fabs()` method takes a decimal (`float`) number as a parameter and returns its absolute value (which is always positive). We also have the global `abs()` function which works with integers.

``````{PYTHON}

import math

print(math.fabs(-2.2))
print(math.fabs(2.2))
print(abs(-2))
print(abs(2))``````

The output:

```Console application
2.2
2.2
2
2```

### `sin()`, `cos()`, `tan()`

These classic trigonometric functions all take an angle as a `float`, which has to be entered in radians (not degrees if your country uses them). To convert degrees to radians we multiply them by `(Math.PI / 180)`. The return value is also a `float`.

### `acos()`, `asin()`, `atan()`

These are inverse trigonometric (arcus, sometimes cyclometric) functions, which return the original angle according to its trigonometric value. The parameter is a `float` and the returned angle is in radians (also as a `float`). If we wanted the angle in degrees, we'd have to divide the radians by `(180 / Math.PI)`.

### `pow()` and `sqrt()`

`pow()` takes two parameters. The first is the base of the power and the second is the exponent. If we wanted to calculate 23, the code for it would be as follows:

``````{PYTHON}

import math

print(math.pow(2, 3))``````

`sqrt()` is an abbreviation for SQuare RooT, which returns the square root of the number given as a `float`. Both functions return a `float` as the result.

``````{PYTHON}

import math

print(math.sqrt(12))``````

### `exp()`, `log()`, `log2()`, `log10()`

`exp()` returns Euler's number raised to the given exponent. `log()` returns the natural logarithm of the given number or the logarithm of the base entered as the second parameter. `log10()` returns the decadic logarithm of the number and `log2()` returns the binary logarithm.

``````{PYTHON}

import math

print(math.log(16, 4))
print(math.log10(1000))
print(math.log2(32))``````

The output:

```Console application
2.0
3.0
5.0```

Hopefully, you noticed that the method list lacks any general root function. We, however, can calculate it using the functions the `math` module provides.

We know that roots work like this: the 3rd root of `8 = 8^(1/3)`. Therefore, we can write the following bit of code:

``````{PYTHON}

import math

print(math.pow(8, (1/3)))``````

## Division

Programming languages often differ in how they perform the division of numbers. You need to be aware of these issues to avoid being, unpleasantly, surprised afterwards. Let's write a simple program:

``````{PYTHON}
a = 5 / 2
b = 5.0 / 2
c = 5 / 2.0
d = 5.0 / 2.0
e = 5 // 2
f = 5.0 // 2
g = 5 // 2.0
h = 5.0 // 2.0

print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
print(h)``````

We divide `5 / 2` several times in the code. Mathematically, it's `2.5`. Nonetheless, the results will not be the same in all cases. Can you guess what we'll get in each case? Go ahead, give it a try The program output will be the following:

```Console application
2.5
2.5
2.5
2.5
2
2.0
2.0
2.0```

We see the result of division using the `/` operator is always decimal (`float`). It doesn't really matter what the data type of the variable we're assigning the result to is. If we wanted to perform whole-number division, we'd have to use the `//` operator. As you can see, it returns decimal numbers for decimal inputs, but the value is always a whole number (`.0`).

### The remainder after division

In our applications, we often need the remainder after integer division (i.e. modulo). In our example `5 // 2`, the integer result is `2` and modulo is `1` (what's left over). Modulo is often used to determine whether a number is even (remainder of division by `2` is `0`). You would use it, for example, to draw a checkerboard and fill in the fields based on whether they are even or odd, calculate the deviance of your position in a square grid, and so on.

In Python, as in C-like languages in general, modulo is a percent sign, i.e. `%`:

``````{PYTHON}
print(5 % 2) # prints 1``````

Well, that's all I've got for today. In the next lesson, Solved tasks for Python lessons 10-12, we'll learn to declare custom functions and to decompose our programs into multiple logical parts.

In the following exercise, Solved tasks for Python lessons 10-12, we're gonna practice our knowledge from previous lessons.

Article has been written for you by David Capka
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to. The author learned IT at the Unicorn University - a prestigious college providing education on IT and economics.

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!