Skip to content

Intermediate · Errors, modules and the standard library · topic 23 of 50 · 20 min

Modules and imports

Explanation

A module is a Python file full of ready-made functions. You load it with import. Python comes with a large standard library, such as math for maths and random for random choices, and any .py file you write is a module too.

What a module is

A module is simply a .py file that holds functions and variables. The standard library is the big set of modules that comes with Python, so you never need to install them. You only import the ones you need.

Think of it like this: Think of the steel dabbas on a kitchen shelf. One holds spices, one holds dal, one holds rice. You open only the dabba you need for today's dish. import math opens the maths dabba; your program does not carry every dabba around.

Three ways to import

python
import math
print(math.sqrt(144))

from math import pi, floor
print(floor(pi))

import statistics as st
print(st.mean([10, 20, 30]))
Shows 12.0, then 3, then 20.
You writeThen you useGood for
import mathmath.sqrt(9)Clear: you see where sqrt comes from
from math import sqrtsqrt(9)A few names you use very often
import statistics as stst.mean(data)A long module name you type a lot

The math module

python
import math
print(math.sqrt(49))       # 7.0
print(math.ceil(4.1))      # 5: round up
print(math.floor(4.9))     # 4: round down
print(round(math.pi, 4))   # 3.1416
ceil always goes up, floor always goes down.
Tip: ceil is perfect for "how many do I need" questions. 130 students and 50 seats per bus need math.ceil(130 / 50) = 3 buses, not 2.6 buses and not 2.

The random module

python
import random
random.seed(7)
print(random.randint(1, 6))                     # a dice roll, 1 to 6
print(random.choice(["chai", "coffee", "lassi"]))
cards = [1, 2, 3, 4, 5]
random.shuffle(cards)                           # mixes the list in place
print(cards)
randint includes both ends. shuffle changes the list itself.

Random numbers on a computer come from a formula that starts from a number called the seed. The same seed always gives the same sequence. That is very useful for testing. random.Random(seed) makes your own private generator, so it does not disturb any other code that uses random.

python
import random
rng1 = random.Random(42)
rng2 = random.Random(42)
print(rng1.randint(1, 100) == rng2.randint(1, 100))
True: same seed, same numbers.
Careful: Never name your own file random.py, math.py or json.py. When you write import random, Python finds your file first and imports it instead of the real module, and you get strange AttributeErrors.

Your own modules and __name__

output
# file: greetings.py
def namaste(name):
    return "Namaste, " + name + "!"

# file: main.py (in the same folder)
import greetings
print(greetings.namaste("Kavya"))
Two files on your computer: main.py imports greetings.py.

Every module has a variable called __name__. When you run a file directly, Python sets its __name__ to "__main__". When the same file is imported by another file, __name__ is the module name, such as "greetings". So code inside if __name__ == "__main__": runs only when you run that file directly, not when it is imported.

python
def namaste(name):
    return "Namaste, " + name + "!"

print("__name__ is", __name__)

if __name__ == "__main__":
    # quick demo: runs only when this file is run directly
    print(namaste("Kavya"))
Run here, the file is the main program, so the demo line runs.
Tip: For passwords and OTPs, use the secrets module, not random. random is predictable on purpose (that is what the seed is for); secrets is built to be hard to guess.

Watch the lesson

Modules and imports · 1/7

Modules and imports

A module is a Python file full of ready-made tools. In this lesson you will import modules and use two of the most popular ones.

Prefer a video by a teacher? Find free videos on “python modules import math random tutorial” on YouTube ↗

In real life: A fair lucky draw at a school fair

Teacher Sunita runs a lucky draw for 8 tickets. She shuffles the tickets with a fixed seed and writes the seed on the notice board. Any parent can run the same code with the same seed and get exactly the same winners, so everyone can see the draw was fair.

python
import random
rng = random.Random(2024)
tickets = ["T1", "T2", "T3", "T4", "T5", "T6", "T7", "T8"]
rng.shuffle(tickets)
print("Winners:", tickets[0], tickets[1], tickets[2])
The same seed gives the same winners every time.

Practice (0/3 done)

Task 1 · Code · Python

Write buses_needed(students, per_bus) that returns how many buses are needed so every student gets a seat. Use math.ceil. buses_needed(130, 50) returns 3.

Task 2 · Code · Python

Write roll_dice(seed, times) that makes a generator with random.Random(seed) and returns a list of `times` dice rolls (each from 1 to 6, using randint). The same seed must always give the same list.

Task 3 · Code · Python

Write circle_area(r) that returns the area of a circle (pi times r times r) rounded to 2 decimal places, using math.pi instead of 3.14. circle_area(7) returns 153.94.

Quick quiz

Question 1

1.What does math.ceil(2.1) return?

Question 2

2.Which import lets you write sqrt(25) without math. in front?

Question 3

3.Why would you call random.seed(10) or use random.Random(10)?

Question 4

4.What is __name__ inside a file that you run directly?

Question 5

5.You saved your lucky draw as random.py and now import random fails strangely. Why?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: Errors and exceptions