LESSON 12

Modules

Learning objective: Reuse code by importing modules.

Understand

Modules give you ready-made tools.

Python's standard library has modules like random, math, and datetime. Bring them in with import. You can also split your own code into modules and import between files.

Analogy: A module is like a toolbox you borrow instead of building every tool yourself.

See It in Action

Using the random module:

import random
print(random.randint(1, 6))  # a dice roll
How it works: import random loads the module, and randint(1, 6) returns a random number like a dice roll.

Try It Yourself

  1. Import the random module.
  2. Generate a random number.
  3. Import math and use math.sqrt.

Quick Quiz

What does import do?

Challenge

Use a standard library module to add a feature to a small script.

Success condition: Your script uses a function from an imported module.