- Load a module with
importandfrom ... import - Apply the main functions of the
mathandrandommodules - Calculate with dates using
datetime
You don't have to write code from scratch to take a square root, pick a random number or count the days between two dates. Python comes with a standard library full of ready-made tools. These tools are grouped into modules — you simply load the one you need and use it.
import and the math module
A separate Python file containing functions, variables and classes. The import statement loads a module into your program, and you reach its parts with a dot: math.sqrt.
import math
print(math.sqrt(144))
print(math.pi)
print(math.ceil(4.2), math.floor(4.8))
print(math.gcd(24, 36))▸ Expected output
12.0 3.141592653589793 5 4 12
ceil rounds a number up, floor rounds it down, and gcd finds the greatest common divisor of two numbers. If you only need a few names from a module, you can take them directly with from ... import — then you don't need to write math. any more:
from math import sqrt, pi
radius = 3
area = pi * radius ** 2
print(f'Circle area: {area:.2f}')
print(sqrt(2))▸ Expected output
Circle area: 28.27 1.4142135623730951
random: random numbers
Games, quizzes and tests need randomness. The most used functions of the random module are: randint(a, b) — a random whole number from a to b (both included), choice(list) — a random item from a list, and shuffle(list) — mixing up a list.
import random
for i in range(3):
print(f'Roll {i + 1}: {random.randint(1, 6)}')Sometimes you need to repeat random results — for example, when testing a program. random.seed() sets the starting point of the sequence: with the same seed, the “random” values come out the same every time.
import random
random.seed(42)
print(random.randint(1, 6))
print(random.choice(['rock', 'paper', 'scissors']))
cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print(cards)▸ Expected output
6 rock [2, 4, 5, 3, 1]
datetime: dates and times
In Azerbaijan the school year starts on 15 September — Knowledge Day. How many days are there from that day to New Year? In the datetime module, date represents a date and timedelta a length of time. Subtracting one date from another gives a timedelta, and its days attribute holds the number of days.
from datetime import date, timedelta
start = date(2026, 9, 15)
new_year = date(2027, 1, 1)
print(start)
print(start.strftime('%d.%m.%Y'))
print((new_year - start).days, 'days until New Year')
print(start + timedelta(days=100))▸ Expected output
2026-09-15 15.09.2026 108 days until New Year 2026-12-24
strftime turns a date into a string in any format you like: %d means day, %m month and %Y year. date.today() gives today's date — so the result of the code below is different every day:
from datetime import date
today = date.today()
print('Today is', today.strftime('%d.%m.%Y'))
print('Days left this year:', (date(today.year, 12, 31) - today).days)What else is in the standard library?
| Module | What it is for |
|---|---|
statistics | mean, median, mode |
collections | extra data structures such as Counter |
string | ready-made character sets: letters, digits |
json | reading and writing data in JSON format |
time | measuring time, waiting |
import statistics
from collections import Counter
scores = [7, 9, 6, 9, 10, 8, 9]
print(round(statistics.mean(scores), 2))
print(statistics.median(scores))
votes = ['pizza', 'plov', 'plov', 'dolma', 'plov', 'pizza']
print(Counter(votes).most_common(2))▸ Expected output
8.29
9
[('plov', 3), ('pizza', 2)]Counter counts the votes in one line.95 pupils are going on a trip, and a bus has 40 seats. Import the math module and print two lines: 1) how many buses are needed (with math.ceil), 2) the area of a round pool with a radius of 3.5 m, with two digits after the point (with math.pi).
pupils = 95
seats = 40
radius = 3.5
# 1) import math
# 2) print how many buses are needed
# 3) print the area of the pool with 2 digits after the point▸ Expected output
3 38.48
Use from ... import to import mean and median from the statistics module and Counter from collections. For the grades list print three lines: the mean, the median and the most common grade in the form Most common: 3 (2 times) (with the real numbers, of course).
grades = [5, 4, 5, 3, 5, 4, 2, 5]
# 1) import mean, median and Counter
# 2) print the mean and the median
# 3) print the most common grade like: Most common: 3 (2 times)▸ Expected output
4.125 4.5 Most common: 5 (4 times)
Key points
- A module is a file of ready-made functions;
import mathloads it andmath.sqrtreaches one of its parts. from math import sqrttakes a name directly, so no dot is needed.random.randint,choiceandshuffleadd randomness;seedmakes the results repeatable.datestores dates; the difference of two dates is atimedelta, and.daysgives the days.- Never give your file the name of a standard module.
Check yourself
10 questions. Every correct answer earns XP.
sqrt from the math module?