Modules

We have previously seen some functions that are built in to the language, like input and print. That is functionality that is common and always available.

But Python comes with even more built-in functions, sparated into different modules. We have already used turtle. We are going to take a look at three useful modules: math, random, time.

Importing modules

To include a module called "math" we write:

import math

A bunch of different mathematics-related things are available through this module. We just need to say we need this module once and can then use everything inside it anywhere in our program. Therefore, we usually put these import instructions at the top of the code.

We can use whatever is inside the math module by first writing its name, then a dot, and then the name of what we need. Se the following example:

import math
# The math module contains constants like pi:
print(math.pi)
# And a function to compute the square root, called sqrt:
square_root_of_nine = math.sqrt(9)
print(square_root_of_nine)

Randomness

Another module is called random, which helps us with everything to do with randomness.

We import it in exactly the same way:

import random

There is a function inside called "randint" which provides a random integer. We can use it to create a digital dice:

import random
dice_roll = random.randint(1, 6)
print(dice_roll)

Run this program a few times. Do you notice how the output changes every time?

If we want a random number with decimals (float) we can instead use a function called uniform:

import random
number = random.uniform(1, 100)
print(number)

Time

A third module we will look at is called time, and as the name suggests it has to do with keeping and managing time. We will look at one function there called sleep, which causes the computer to wait before proceeding with the next instruction.

Try the following example:

import time
print(“Good...”)
time.sleep(2)  # The computer stops here for two seconds
print(“...bye!”)

Run the program. Notice that the "Good..." appears directly, but it takes another two seconds before the "...bye!" is shown.

We can of course use several modules in the same program. Read the following code and try to guess what it does before you run it:

In the next chapter we will use these modules, primarily random, to create a real game!

Read page in other languages

In this video, we combine two modules, random and turtle, to draw multiple rectangles of random sizes.

  • Function: Small and reusable parts of our code, for example input and print. Sometimes referred to as methods.
  • Module: We can reuse code that others have written, in our programs. To not get overwhelmed by all the code, we divide it up into modules that can be imported as needed. A module contains one or more functions.