…
…
Python Programming Fundamentals · Lesson 36 / 40 · Modules and the standard library
PreviewIn this lesson you will
dir and help, and use it with the right import formceil, floor, round), the mean or the median, and a fixed-seed random choice for the jobYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Ada wants to add the average and median order amounts to the end-of-day report, calculate the cup packs by rounding up, and pick a random promotion item every day. Instead of writing all of this from scratch, we will use the ready-made modules that come with Python.
The program you write by the end of this lesson will produce this report from the day's order amounts:
OutputAverage basket: $9.54
Median basket: $5.00
Cup packs: 84
Today's promotion: latteEach of the four lines looks like a small calculation, but each one hides a trap. You can find the average with a loop yourself; for the median you would have to sort the list and pick the middle value, and if the number of items is even, take the average of the middle two. If you use round in the pack calculation, some days you will come up one pack short. To pick a random item, you need to know how a computer produces "random". In this lesson you will learn to find the ready-made tools that do these jobs for you, bring them into your program, and choose the right one.
Python is known as a "batteries included" language: hundreds of ready-made tools come with the installation. These tools are organized into modules. A module is a Python file that contains functions and values. All the modules that come with Python are together called the standard library. To use a module, you first have to import it into your program. You have already done this: you wrote import csv in lesson 34 and import json in lesson 35. In this lesson we will look closely at what that line does and meet three new modules: math for math, statistics for basic statistics, and random for random choices.
Why use a ready-made module? Because every function you write from scratch is new code you have to test. The functions in the standard library have worked in millions of programs for years; the edge cases (an empty list, a negative number, an even number of items) have already been thought through. Your job is to find the tool that fits the task and use it correctly.
There are three ways to bring a module into your program. All three reach the same function; the difference is the name you use to call it afterward.
| Syntax | Usage | When |
|---|---|---|
import math | math.ceil(2.1) | When you will need many functions of the module |
from math import sqrt, ceil | sqrt(16) | When you will need only a few functions |
import statistics as st | st.median(...) | When the module name is long and you want a short alias |
import math brings the whole module and adds a single new name to your program: math. You reach the functions by putting a decimal point after this name: math.ceil, math.sqrt. This prefix tells the reader where the function comes from; a year later, someone who looks at the code and sees math.ceil understands it without searching. from math import sqrt brings only the functions you list from the module; you call them without a prefix. With as, you give the module a short alias. By convention, import lines are written at the very top of the file, so what the program depends on is visible at first glance.
Example 1 (case): The three forms side by side
import math print(math.ceil(250 / 3)) from math import sqrt print(sqrt(16)) import statistics as st print(st.median([3, 1, 2]))
Output84
4.0
2The point that causes the most confusion is this: each form adds different names to the program. import math adds only the name math; it does not add a name sqrt. from math import sqrt adds only the name sqrt; it does not add a name math. If you write only from math import sqrt in a new program and then try to use math.ceil, Python does not recognize that name:
from math import sqrt print(sqrt(16)) print(math.ceil(2.1))
Error:
Output4.0
NameError: name 'math' is not defined. Did you forget to import 'math'?Remember from lesson 17: a NameError means "I don't recognize this name." The first line ran and 4.0 was printed; on the third line Python looked for the name math and could not find it. Python 3.14 also makes a suggestion here: "Did you forget to import 'math'?" What about the other way around? Predict first.
What happens when this code runs?
import math print(sqrt(16))
The rule in short: you use the name you imported. Below, match each import line with the call that works after that line.
Which call works after each import line?
For each row, pick its match from the list, then check.
import mathfrom math import floorimport math as mfrom math import floor, ceilYou do not need to memorize how many functions the math module has; Python tells you when you ask. You met help() in lesson 5. With modules, you use two tools together: dir(module) gives all the names in the module as a list, and help(module.name) explains what that name does. dir(math) returns more than 60 names; instead of reading the list from start to finish, you can ask whether a name you are looking for is in it with in:
import math print("ceil" in dir(math)) help(math.ceil)
OutputTrue
Help on built-in function ceil in module math:
ceil(x, /)
Return the ceiling of x as an Integral.
This is the smallest integer >= x.The help text looks crowded at first glance, but it is always written in the same order. Read it in three steps:
1. The signature (ceil(x, /)): How many parameters does it take? Here, a single x. You can ignore the / at the end for now; it means "give the argument by position, not by name."
2. The first sentence: What does it return? "Return the ceiling of x as an integer." The next sentence defines the ceiling: the smallest integer greater than or equal to x.
3. Try it: Run it on a small example and see with your own eyes that the result matches what it says.
This third step matters, because tools that seem to do the same job separate in edge cases. Ada's question is "250 cups come in packs of 3; how many packs should I buy?" Let's try four tools:
Example 2 (case): The same division, four tools
import math print(math.ceil(250 / 3)) print(math.floor(250 / 3)) print(round(250 / 3)) print(int(250 / 3)) print(math.sqrt(16), round(math.pi, 2))
Output84
83
83
83
4.0 3.14250 / 3 = 83.33... ceil rounds up and floor rounds down. round goes to the nearest integer, which for 83.33 is 83. int cuts off the decimal part and also gives 83. But 83 packs is 249 cups; one customer is left without a cup. The answer to "how many packs?" must always be rounded up; round or int gives the wrong result here. The last line shows two more familiar tools from the math module: math.sqrt for the square root, and math.pi for the number pi (this is not a function but a value; it takes no parentheses).
The real trap is here: round gives the right result on most days, so the mistake goes unnoticed. Change the number of people and see when the two tools differ.
Change the value of people. At which value do round and math.ceil give different results?
Pick a value; predict the output first, then look.
1import math2people = 2503print(round(people / 3), math.ceil(people / 3))
83 84
Faded lines didn't run with this value. 249 and 6 divide evenly, so the two tools give the same result. 251 / 3 = 83.67 rounds up to the nearest integer, so again the same. But at 250 / 3 = 83.33, round goes down and reports one pack too few. The same result in three of the four tries does not show that round is the right tool; if the question is "nobody should be left short", the answer is ceil.
| People | people / 3 | round | math.ceil | Enough? |
|---|---|---|---|---|
| 249 | 83.0 | 83 | 83 | Both are enough |
| 250 | 83.33 | 83 | 84 | round is one pack short |
| 251 | 83.67 | 84 | 84 | Both are enough |
| 6 | 2.0 | 2 | 2 | Both are enough |
The question of the job decides the choice. If it says "nobody should be left short", use ceil. If it says "exactly how many boxes got filled?", use floor (the same as // for positive numbers). If it says "write the price to the nearest whole dollar", use round.
Now let's move to the first two lines of the report. The statistics module offers three basic tools: mean for the average, median for the middle value (the one left in the middle when the values are sorted), and mode for the most frequent value. Let's start with Ada's five orders today, then add a single large order that arrives in the afternoon:
Example 3 (case): What does one large order change?
from statistics import mean, median amounts = [8.50, 3.75, 3.75, 6.25, 3.00] print(mean(amounts), median(amounts)) amounts.append(32.00) print(round(mean(amounts), 2), median(amounts))
Output5.05 3.75
9.54 5.0With five orders, the average is $5.05 and the median is $3.75. When an office places a $32.00 bulk order, the average almost doubles to 9.54; the median moves from 3.75 to 5.0. With six orders, two values remain in the middle (3.75 and 6.25), so the median is their average. Five of today's six customers spent less than $9.54; so here the average does not describe the "typical customer". The median is affected much less by extreme values than the mean: a single large order can inflate the average but barely changes the median. The average does not always give the typical value. Writing both in the report also shows how a few large orders affect the day. You will see these ideas in detail in the Basic Statistics and Data Analysis course.
The same tools work for prices and item names:
from statistics import mean, median, mode prices = [4.25, 1.25, 3.75, 2.75] print(mean(prices), median(prices)) print(mode(["latte", "tea", "latte"]))
Output3.0 3.25
lattemode also works with values that are not numbers: it is perfect for finding the best-selling item. But if two items sold the same number of times, which one does mode return? The answers to questions like this are always in the help text; you can type help(statistics.mode) and read it. Now it is your turn. The cell below prints the help text of a math function you have never seen and uses it once.
Try it now· not graded; doesn't affect progress
The first sentence is "Calculate the product of all the elements in the input iterable", that is, it multiplies all the elements of the sequence you give it. 3 × 4 × 2 = 24 different drinks. You did not know this function before; by reading the help text and trying it on one example, you started using it in two minutes. This is the real skill of working with modules. Now match the right tool to each job.
Which tool for each job?
For each row, pick its match from the list, then check.
random and seedThe last line of the report picks the promotion item of the day at random. The random module has three basic tools: random.choice(list) gives a random item from a list; random.randint(a, b) gives a random integer between a and b, and both ends are included (randint(1, 6) is like a die: 1 and 6 can both come up); random.shuffle(list) shuffles a list. shuffle changes the list in place and returns None, like sort in lesson 24; instead of assigning the result to a variable, you look at the list itself.
So how does a computer pick at random? In fact, it does not pick; it calculates. The random module starts from a starting number and produces a long sequence of numbers that looks irregular from the outside. This starting number is called the seed. Normally Python takes the seed from something that changes with every run (for example, the current time), so the results are different each time. If you write random.seed(7), you fix the seed yourself, and the program produces the same "random" sequence every time it runs. This makes the results repeatable.
Example 4 (outside the case): The same seed, the same dice
import random random.seed(7) a = [random.randint(1, 6) for roll in range(5)] random.seed(7) b = [random.randint(1, 6) for roll in range(5)] print(a, b, a == b)
Output[3, 2, 4, 6, 1] [3, 2, 4, 6, 1] TrueNotice: seed did not remove the randomness. Each of the five dice came up different: 3, 2, 4, 6, 1. The seed only fixed the starting point of the sequence; two sequences that start from the same seed are identical step by step. The misconception "once you set a seed, every call gives the same number" comes from here; the correct version is "once you set a seed, the same sequence repeats from the start."
Why would we want this? Because to test that a program with randomness works correctly, the result has to be known in advance. In tests and in the exercises on this site, every piece of code with randomness runs with a fixed seed; that way the check can compare your output with the expected output. When you find a bug, you can also reproduce the same situation with the same seed. Back to the case:
Example 5 (case): The promotion of the day
import random random.seed(7) items = ["latte", "tea", "brownie", "lemonade"] print(random.choice(items)) print(random.randint(1, 20))
Outputbrownie
5Whenever you run this code, you get brownie and 5. One more thing: after the seed, the order of the calls also decides the result. Each choice and randint call takes the next number in the sequence; if you change the order, each call gets a different number. Try it yourself below.
Try it now· not graded; doesn't affect progress
With the seed on, every run gives 84 and 6 tea. When you turn off the seed line, the last line changes every time; 84 never changes, because math.ceil is not random. In the third try you see bagel 1: the same seed, but this time choice took the first number of the sequence and randint took the second.
Now let's combine the three ideas and write the report from the start of the lesson. The imports are at the top; the report is in a function (lesson 14), so it can be called with another day's amounts; the promotion is picked with a fixed seed. For the average, we print two decimal places (:.2f) with the formatting from lesson 22.
Example 6 (case): The target program of the lesson
# 1. Import import math import random from statistics import mean, median # 2. The day's amounts amounts = [8.50, 3.75, 3.75, 6.25, 3.00, 32.00] # 3. Report function def end_of_day(amounts, people, pack_size): print(f"Average basket: ${mean(amounts):.2f}") print(f"Median basket: ${median(amounts):.2f}") print(f"Cup packs: {math.ceil(people / pack_size)}") end_of_day(amounts, 250, 3) # 4. Promotion random.seed(2026) promotion = random.choice(["latte", "tea", "brownie", "lemonade"]) print("Today's promotion:", promotion)
OutputAverage basket: $9.54
Median basket: $5.00
Cup packs: 84
Today's promotion: latteInside the function, mean, median, and math.ceil were used in three different ways, but all of them depend on the imports at the start of the program: mean and median came with from, so they have no prefix, and ceil came with import math, so it has the math. prefix. Below, put the five lines of the target program in the right order. Assume that the lines from statistics import median and amounts = [...] are already written; their place is free, so they are not part of the ordering.
Put the lines of the end-of-day report in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The ceil decision is not specific to the café; it is the same in every job that asks "how many do we need so nobody is left out?" 47 students are going on a school trip, and the rented buses hold 15 people.
Example 7 (outside the case): How many buses?
import math students = 47 capacity = 15 print(math.ceil(students / capacity), "buses") print(round(students / capacity), int(students / capacity), students // capacity)
Output4 buses
3 3 347 / 15 = 3.13. round, int, and // all say 3; 45 students fit on 3 buses and 2 students are left on the road. The right answer is 4. Finally, test the limits of ceil and floor: what do they do with numbers very close to an integer and with negative numbers?
What does this code print?
import math print(math.ceil(7.01), math.floor(7.99), math.ceil(-1.5))
These three notes are not in the test, but they will help you when you write programs on your own computer.
You can also collect your own functions in a module. For example, if you write the end-of-day functions in a file named reporting.py, you can use them in another program in the same folder by writing import reporting and calling them as reporting.revenue(...). A large program is split into meaningful files like this, and the same function is reused in many programs. The exercises on this site are single-file, so you should try this on your own computer:
# reporting.py def revenue(orders): return sum([o["quantity"] * o["price"] for o in orders])
Ada wants to put a different item on promotion each day of the week; the order should be random but repeatable. shuffle shuffles the list in place and returns None: if you assign the result to a variable, you are left with None; the shuffled order is in the list itself.
import random random.seed(3) items = ["latte", "tea", "brownie", "lemonade", "bagel"] result = random.shuffle(items) print(result) print(items)
OutputNone
['latte', 'brownie', 'lemonade', 'bagel', 'tea']A farm collects 100 eggs a day, and the cartons hold 30. The same division answers three different questions with three different tools: how many cartons got filled (floor or //), how many cartons are needed to carry them all (ceil), and how many eggs are left over (%).
import math eggs = 100 carton = 30 print("Full cartons:", math.floor(eggs / carton), eggs // carton) (, math.ceil(eggs / carton)) (, eggs % carton)
Importing a module and then calling the function without the prefix. After writing import math, it feels very natural to call the function directly:
import math print(sqrt(16))
Error:
OutputNameError: name 'sqrt' is not definedimport math adds only the name math to the program; there is no name sqrt. There are two correct fixes, so choose one of them: either add the prefix (print(math.sqrt(16))), or change the import line (from math import sqrt, then print(sqrt(16))). Do not mix the two: if you write from math import sqrt and then say math.sqrt(16), this time the name math is undefined.
import math → math.ceil(...), from math import ceil → ceil(...) (but the name math is undefined), import statistics as st → st.median(...): you use the name you imported.dir and help (signature, first sentence, try it) and choose it by the question of the job: "nobody left short" is ceil, "exactly how many filled" is floor, "nearest" is round; when there are extreme values, put the median next to the average.random.choice, randint (both ends included), and shuffle pick at random; random.seed(n) makes the same sequence repeat from the start, and the order of the calls also decides the result.Next lesson: Two more modules: datetime, which does calculations with dates and times, and collections
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputFull cartons: 3 3
Cartons needed: 4
Eggs left over: 10