Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 15 min

Modules: don't reinvent the wheel

By the end of this chapter, you'll be able to

  • Import a module with import
  • Import only some names with from … import
  • Use the math, random and datetime modules
  • Explain how to split your own program into modules

import

A module is a Python file that groups functions and variables. The import statement loads it, then you access its contents with a dot:

import math

print(math.sqrt(49))        # square root
print(math.pi)              # a constant from the module
print(math.ceil(2.1))       # rounds up to the next integer
7.0
3.141592653589793
3

With from module import name, you import one specific name and use it without a prefix:

from datetime import date

start = date(2026, 1, 15)
end = date(2026, 3, 1)
print((end - start).days, "days")
45 days

Without seed, each run would give different values.

Step 5 of 5
Text description of the animation
  1. We simulate three dice rolls with the random module.
  2. import random loads the module: its functions become available with random.
  3. seed fixes the generator's seed: the "randomness" will be the same on every run, which is handy for testing.
  4. randint(1, 6) draws an integer between 1 and 6 inclusive, three times. With seed 42, we always get 6, 1, 1.
  5. Without seed, each run would give different values.
import random
random.seed(42)
rolls = [random.randint(1, 6) for _ in range(3)]
print(rolls)
print(random.choice(["rock", "paper", "scissors"]))
[6, 1, 1]
scissors

Line 3 uses a list comprehension: [expression for variable in sequence] builds a list in one line. The name _ signals that the loop variable isn't used.

Your own modules

In a real project, the code is split into several files. If you create a file tools.py containing def vat(price): ..., another file in the same folder can write from tools import vat. Each file then keeps a single responsibility, and testing is simpler.

So that a file can be imported and run directly, we protect its demo code:

def vat(price, rate=0.2):
    return round(price * rate, 2)

if __name__ == "__main__":
    # this block only runs if you launch this file directly,
    # not when another file does "from tools import vat"
    print(vat(50))
10.0

Your turn

Mini-lab: the random passwordPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Worked exercise: age in days

With the datetime module, write a function age_in_days(birth, today) that returns the number of days between two dates. Test it with a birth on 1 May 2010 and the date 1 May 2026.

Hint 1
from datetime import date, then date(2010, 5, 1).
Hint 2
The difference between two dates has a .days attribute.
Show the solution and common mistakes
from datetime import date

def age_in_days(birth, today):
    return (today - birth).days

print(age_in_days(date(2010, 5, 1), date(2026, 5, 1)))
5844

16 years make 5,844 days because the period contains 4 leap years (2012, 2016, 2020 and 2024).

Common mistakes:

  • Using date.today() inside the function: the result would change every day and the function would be impossible to test. It's better to receive the date as a parameter.
  • Writing date(2010, 05, 01): in Python, a non-zero integer can't be written with a leading zero, so it's a SyntaxError.

Summary

  1. 1import module loads a module; you then use module.name.
  2. 2from module import name imports one specific name, usable without a prefix.
  3. 3math, random and datetime cover very common needs.
  4. 4An if __name__ == "__main__" block only runs if the file is launched directly.
  5. 5Never give a file the same name as a standard module.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.