Lesson 19 of 30

In progress

Course progress

Python

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, datetime and statistics for common jobs.
  • Protect script code with the __main__ guard.

Three ways to import

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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 module keeps names qualified; from module import name is shorter but can collide.
  • math, random, datetime and statistics cover most early needs, and seed makes 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?
No. It ships with Python. Third-party packages are a separate step with pip, and this track deliberately avoids them so every example runs anywhere.
Why does randint include the upper number but range does not?
They follow different conventions: `randint(a, b)` is documented as inclusive, while `range(a, b)` is a sequence that stops before `b`. Check the documentation for each function rather than assuming they match.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.