Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 149 ยท Modules and the Standard Library

math and random

Use Python's math module for roots, rounding, logs and trigonometry, generate random numbers and choices with random, and summarize data with statistics.

Python's built-in operators handle everyday arithmetic, but real programs soon need more: square roots, logarithms, angles, a fair dice roll, a random sample, or the median of a list. Three standard-library modules cover these: math for precise mathematical functions, random for unpredictability, and statistics for summarizing data.

None of them needs installing. Import them and they're ready, as you saw in Modules and Imports.

The math module

math provides constants and functions that work on regular int and float values:

Python math essentials

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few notes:

  • math.sqrt() raises ValueError for negative numbers. For complex results, use the cmath module.
  • math.isqrt() stays in exact integers, which matters for huge numbers where a float would lose precision.
  • math.cbrt() was added in Python 3.11.

Rounding toward a direction

Python's built-in round() rounds to the nearest value (with ties going to the even number, as covered in Numbers). math adds rounding in a fixed direction:

Python floor, ceil and trunc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

floor() always goes down, ceil() always goes up, and trunc() chops off the decimal part, so it goes toward zero. The difference shows up only with negative numbers.

Logarithms, trigonometry and float checks

Python logs, angles and comparisons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use math.isclose() whenever you compare floats that came out of calculations. It treats two numbers as equal when they differ by a tiny relative amount (by default, one part in a billion), and you can loosen that with rel_tol or abs_tol.

Two counting functions are handy for probability puzzles: math.comb(n, k) counts the ways to choose k items from n when order doesn't matter, and math.perm(n, k) counts them when order does. math.comb(49, 6) gives the 13,983,816 possible lottery tickets in a 6-of-49 draw.

The random module

random generates pseudo-random numbers: sequences that look random but come from a deterministic algorithm (the Mersenne Twister). They're great for games, simulations, sampling and shuffling.

Python Random numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Run it a few times; every run prints different numbers. Watch the edges: randint(1, 6) can return 6, but randrange(1, 6) cannot, because it follows the same "stop is excluded" rule as range().

Picking from sequences

Most of the time you don't want a bare number; you want a random item:

Python choice, choices, sample, shuffle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Function Returns Repeats?
choice(seq) one item โ€”
choices(seq, k=n) a list of n items yes
sample(seq, k=n) a list of n items no
shuffle(list) None (changes the list) โ€”

shuffle() returns None. Writing deck = random.shuffle(deck) throws your list away. Call it on its own line, or use random.sample(deck, k=len(deck)) to get a shuffled copy.

Seeds: reproducible randomness

Because the generator is deterministic, giving it the same starting point, the seed, produces the same sequence every time. That's invaluable for tests, debugging and repeatable simulations:

Python Seeding the generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Creating your own random.Random(seed) object is the tidy option in larger programs: a seeded generator for a simulation won't be disturbed by other code that also calls random.

Security: use secrets, not random

The random module is predictable by design. Someone who sees enough outputs can work out what comes next, so never use it for passwords, tokens, or anything security-related. The secrets module draws from the operating system's secure source instead:

Python The secrets module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The statistics module

For quick descriptive statistics, you don't need a big data library. statistics handles lists of numbers directly:

Python Summary statistics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how one unusual day (120 minutes) pulls the mean up while the median barely moves. That's why reports often prefer the median for things like house prices or response times.

The module also has fmean() (a fast float mean), pstdev() and pvariance() for whole populations (versus stdev() and variance() for samples), correlation() and linear_regression() for pairs of lists. For large arrays or heavy number crunching, numpy is the usual next step.

Common pitfalls

A few mistakes show up again and again with these modules:

  • Forgetting the import or the prefix. After import math, the function is math.sqrt, not sqrt. If you see NameError: name 'sqrt' is not defined, either add the prefix or use from math import sqrt.
  • Degrees vs radians. math.sin(90) is not 1, because 90 is read as radians. Convert first with math.radians(90).
  • Empty sequences. random.choice([]) raises IndexError, and statistics.mean([]) raises StatisticsError. Check that your data isn't empty before summarizing it.
  • Asking sample() for too much. random.sample(items, k=10) fails with ValueError if items has fewer than 10 elements, because it can't pick without repeats.
  • Reseeding inside a loop. Calling random.seed(1) on every iteration restarts the sequence each time, so you get the same "random" number again and again. Seed once, at the start.

Also remember math.prod(), the multiplication counterpart of sum(): math.prod([2, 3, 4]) is 24.

Putting it together: a dice simulation

Here's a short experiment that uses all three modules. It rolls two dice many times and checks how often each total appears:

Python Two-dice simulation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Seven comes up most often, because more dice combinations add up to it than to any other total. Change the seed or the number of rolls and watch the shape stay roughly the same.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does math.floor(-2.5) return?

    floor() always rounds down, toward negative infinity, so -2.5 becomes -3. trunc() would give -2.
  2. 2. Which call can return the number 10?

    randint() includes both ends. randrange() and range() exclude the stop value, and random() is always below 1.0.
  3. 3. You need 5 different winners from a list of names. Which function fits?

    sample() never picks the same item twice. choices() samples with replacement, so a name could win twice.
  4. 4. Why does calling random.seed(1) before generating numbers help when testing?

    A seed fixes the generator's starting state. Same seed, same sequence.
  5. 5. Which module should you use to generate a password-reset token?

    random is predictable. secrets uses the operating system's secure random source and is designed for tokens and passwords.

Summary

  • math offers constants (pi, e), roots (sqrt, isqrt), directional rounding (floor, ceil, trunc), logs, trig in radians, and isclose() for comparing floats.
  • random gives numbers (random, randint, uniform) and picks (choice, choices, sample, shuffle); shuffle() works in place and returns None.
  • random.seed() or a random.Random(seed) object makes results reproducible.
  • Use secrets, never random, for passwords and tokens.
  • statistics computes mean, median, mode, standard deviation and quantiles; the median resists outliers.

Next: Dates and Times, where you'll work with dates, durations, formatting and time zones.