Intermediate · Errors, modules and the standard library · topic 23 of 50 · 20 min
Modules and imports
Explanation
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.
Three ways to import
import math
print(math.sqrt(144))
from math import pi, floor
print(floor(pi))
import statistics as st
print(st.mean([10, 20, 30]))| You write | Then you use | Good for |
|---|---|---|
| import math | math.sqrt(9) | Clear: you see where sqrt comes from |
| from math import sqrt | sqrt(9) | A few names you use very often |
| import statistics as st | st.mean(data) | A long module name you type a lot |
The math module
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.1416The random module
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)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.
import random
rng1 = random.Random(42)
rng2 = random.Random(42)
print(rng1.randint(1, 100) == rng2.randint(1, 100))Your own modules and __name__
# file: greetings.py
def namaste(name):
return "Namaste, " + name + "!"
# file: main.py (in the same folder)
import greetings
print(greetings.namaste("Kavya"))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.
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"))Watch the lesson
Modules and imports · 1/7
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.
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])Practice (0/3 done)
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.
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.
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
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.