Lesson 19 of 30
In progress
The standard library: maths, dates and randomness
Import modules correctly, use math, random, datetime and statistics, and run a file as a script without side effects.
Python ships with a large library that is already installed. Knowing four modules covers most beginner needs, and knowing how imports work stops a whole category of confusing errors.
What you will learn
- Import a module, a name from a module, and an alias.
- Use
math,random,datetimeandstatisticsfor common jobs. - Protect script code with the
__main__guard.
Three ways to import
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(math.sqrt(16))
print(date(2026, 1, 1).year)
print(stats.mean([2, 4, 6]))
Press Run to see the output.
The first form keeps everything under the module name, which is the clearest in a long file: math.sqrt tells the reader where sqrt came from. The second imports one name directly, which is shorter but can collide with your own. The third renames the module, useful for long names or established conventions such as import numpy as np.
Avoid from math import *. It dumps dozens of names into your namespace, hides where they came from, and can silently overwrite your variables.
Maths you would otherwise write by hand
math covers roots, rounding, constants and trigonometry.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(math.sqrt(81))
print(math.floor(3.9))
print(math.ceil(3.1))
print(round(math.pi, 4))
print(math.gcd(18, 24))
Press Run to see the output.
round is a built-in and uses banker’s rounding at exact halves; math.floor and math.ceil always move down or up. Use the one that matches the rule you mean, especially with money.
Random numbers, and reproducible ones
random produces pseudo-random values. randint includes both ends, choice picks one item, and shuffle reorders a list in place.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
random.seed(42)
print(random.randint(1, 6))
print(random.choice(["rock", "paper", "scissors"]))
deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)
Press Run to see the output.
seed makes the sequence repeatable, which is essential for tests and demos. Never use random for passwords or security tokens; the secrets module exists for that.
Dates without arithmetic gymnastics
datetime handles dates, times and differences. date.today() gives the local date, and subtracting two dates gives a timedelta with a days attribute.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
start = date(2026, 1, 1)
end = date(2026, 3, 15)
gap = end – start
print(gap.days)
print(start + timedelta(days=30))
print(start.strftime("%d %B %Y"))
Press Run to see the output.
strftime formats for display, and strptime parses text into a date. Keep dates as date objects while calculating and convert to text only when printing; string arithmetic on dates goes wrong at month boundaries.
Summary statistics without a loop
statistics gives mean, median and mode, and it raises clear errors on empty input.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
scores = [72, 88, 91, 65, 50, 88]
print(statistics.mean(scores))
print(statistics.median(scores))
print(statistics.mode(scores))
print(statistics.pstdev(scores))
Press Run to see the output.
The median is the middle value after sorting, so it is less affected by one huge outlier. When a report says "average", decide which one you mean; for salaries and response times, median is usually the honest choice.
Paths without string surgery
pathlib treats a path as a value rather than a string, which avoids a pile of os.path.join calls and separator bugs.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
folder = PurePath("content") / "courses" / "python"
lesson = folder / "01-install-python.md"
print(lesson)
print(lesson.name)
print(lesson.suffix)
print(lesson.parent)
Press Run to see the output.
PurePath does no file access, which makes it safe to demonstrate anywhere. On a real machine, Path adds reading, writing and directory listing. The / operator joins parts and uses the right separator for the operating system, so the same code works on Windows and Linux.
Running a file as a script or importing it
When Python imports a file, it runs the top-level code. That is why library modules guard their script behaviour.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
if __name__ == "__main__":
main()
Press Run to see the output.
__name__ is "__main__" when the file is run directly, and the module name when it is imported. The guard means importing your file for one function does not start a program. Put definitions above the guard and the calls inside main().
Naming your own file random.py or math.py shadows the standard library. The import then loads your file, and the error is confusing because the module "exists". Never name a script after a module you import; dice_game.py is safer than random.py.
Simulate 200 dice rolls with a fixed seed, then print the mean, the median, the most common result and the percentage of sixes. Round the percentage to one decimal place.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
random.seed(7)
rolls = [random.randint(1, 6) for _ in range(200)]
print("Mean:", round(statistics.mean(rolls), 2))
print("Median:", statistics.median(rolls))
print("Most common:", statistics.mode(rolls))
print("Sixes:", round(rolls.count(6) / len(rolls) * 100, 1), "%")
Press Run to see the output.
The seed makes the numbers repeatable, so your output can be compared with a classmate’s. count works because a list of rolls is still a list.
Recap
import modulekeeps names qualified;from module import nameis shorter but can collide.math,random,datetimeandstatisticscover most early needs, andseedmakes randomness repeatable.- The
__main__guard separates reusable definitions from script behaviour.
Next, you will handle the errors that real input produces, instead of letting them end the program.
Do I need to install the standard library?
Why does randint include the upper number but range does not?
Progress is saved in this browser only. No account, no email.