Python · Stage 8 – Organizing Bigger Programs · Lesson 41 of 50

Modules and Imports

Reuse code from another Python file through one explicit import.

Python includes a module named math:

import math
Line-by-line explanation
  1. import tells Python to load a module.
  2. math is the module name.
  3. Its tools are now available through that name.
answer = math.sqrt(25)
Line-by-line explanation
  1. math. selects something from the module.
  2. sqrt calculates a square root.
  3. answer stores 5.0.

Tiny Practice

Import the random module.

Starter template

CHANGE_ME random
Line-by-line explanation
  1. The line needs Python’s import keyword.
  2. Random is the module name.
Hint
  1. The keyword begins with i.
  2. Do not use quotes.
  3. Use one space.
Show Solution
import random
Line-by-line explanation
  1. Import is the instruction.
  2. Random is the requested module.
  3. Its tools can now be accessed with random..