Modules and Imports in Python
Modules are files of ready-made code. Python ships with a large standard library for math, random numbers, dates and much more.
What is Modules and Imports?
Modules are files of ready-made code. Python ships with a large standard library for math, random numbers, dates and much more.
Use Python's standard library with import, from ... import and aliases.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
Example code
# import loads a module from Python's standard library.
import math
import random
from datetime import date
from collections import Counter as Tally
print(math.sqrt(16))
print(math.pi)
print(math.floor(3.7), math.ceil(3.2))
# A fixed seed makes the "random" numbers repeat on every run.
random.seed(1)
print(random.randint(1, 6))
print(random.choice(["rock", "paper", "scissors"]))
print(date(2026, 1, 1).strftime("%A"))
# "as" gives an imported name a shorter or clearer alias.
print(Tally("banana").most_common(1))
Expected output
4.0
3.141592653589793
3 4
2
scissors
Thursday
[('a', 3)]
How it works
import math keeps the module name as a prefix, from datetime import date brings one name in directly, and as gives an import a shorter alias. random.seed makes the random results repeat.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges