Skip to the workspace
Pebellslearn by building
The Standard Toolbox  ›  Lesson

math and random

Math and Random 18 minmath supplies mathematical operations. random supplies pseudo-random sequences whose state can be controlled for reproducible experiments.

math supplies mathematical operations. random supplies pseudo-random sequences whose state can be controlled for reproducible experiments.

Use numerical helpers and independent seeded generators while keeping reproducibility separate from security or unpredictability.

A bus calculation must round a partly filled bus upward; a replayable simulation must consume the same pseudo-random sequence in the same order. Both need a precise contract. Use math for the intended numeric operation and random for controlled simulations, checking input boundaries and reproducibility rather than trusting plausible-looking numbers.

A locked dial labelled random.seed(1) pointing at a row of dice 2,5,1,3 with an identical second row below it in green, next to a dashed row of different dice after random.seed(2) — same seed, same rolls, every time

Split a bill into whole rupees

Three friends split a ₹100 bill. Whole rupees only — no one wants to deal in paise for a group split:

python

// (and divmod) always rounds toward negative infinity — math.floor does the same thing for a value that's already a float. That's not the same as int(), which chops off the decimal part toward zero instead:

What does this print?
import math

print(math.floor(-1.5), int(-1.5))

math.ceil rounds the other way — useful the moment "some left over" means you need one more of something, like a bus:

python

Preparing this topic’s interactive investigation…

Simplify a ratio

A recipe scales 18 eggs to 24 cups of flour, and the app wants to show that ratio in its simplest form. Dividing both sides by the first small number that comes to mind looks like a fix, but isn't always the whole fix:

What does this print?
a, b = 18, 24
a, b = a // 2, b // 2
print(a, b)

math.gcd finds the greatest common divisor directly, so dividing by it always reduces a ratio all the way in one step:

python

Shuffle a deck reproducibly for a demo

A card game needs a shuffled deck — varied for a player, but a demo recording or an automated test needs the same shuffle every time it runs:

python

Run that box again: same three lines, every time, because random.seed(1) was called first. Without resetting the seed, repeated runs normally produce different draws — fine for a real game, but then a predict block about the output would have no single right answer.

random.choice picks one item from a sequence — the seed fixes that pick too:

python

One more from math: sqrt is the one most people already expect, and it's a plain function call, not an operator:

python

Reproduce an experiment without sharing its random state

A seed identifies the start of a pseudo-random sequence. The sequence also depends on which operations consume it and their order. One extra draw can change everything that follows. Separate Random instances give separate state, just as separate closure factories give separate counters.

python

This prints True. Calling random.seed inside a reusable library function would instead reset state shared with unrelated code. The exercise uses the module API so its contract stays simple; an application can inject its own generator. Record the seed, Python version, input order and operation sequence when reproducing an experiment. Shuffle and integer-selection algorithms are not promised identical across all Python versions. Security tokens require secrets, not a predictable seeded simulation generator.

Math functions also have contracts. For non-negative counts and positive capacity, (people + capacity - 1) // capacity gives an exact integer ceiling without converting a huge count to float. gcd(0, 0) is zero, so simplifying 0:0 requires a stated policy before division. For floating-point comparisons near zero, choose an absolute tolerance with math.isclose; display rounding is not a general equality test.

Quick practice

What does this print?
import random

random.seed(7)
a = random.randint(1, 100)
random.seed(7)
b = random.randint(1, 100)
print(a == b)
broken — fix it

The output should show a price one paisa under a whole rupee (₹249.99), not ₹250 unchanged. floor is the wrong tool here — replace it.


🎯 Your turn

Write seeded_dice_rolls(seed, n). Seed the random module with seed, then roll a 6-sided die n times (random.randint(1, 6) each time) and return the list of results, in order.

  • seeded_dice_rolls(1, 5) → [2, 5, 1, 3, 1]
  • seeded_dice_rolls(7, 0) → []

Hint: call random.seed(seed) once, first. Then a list comprehension: [random.randint(1, 6) for _ in range(n)].

Press ▶ Run and hit ✓ Check. ✅

Your task
Write seeded_dice_rolls(seed, n): seed the random module with seed, then roll a 6-sided die n times (random.randint(1, 6) each time) and return the results in order. Example: seeded_dice_rolls(1, 5) -> [2, 5, 1, 3, 1].

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upHow many buses

Write buses_needed(people, capacity) returning how many buses of capacity seats are needed to move everyone — a partly-full bus still counts as one whole bus.

ceil
DrillFully simplify a ratio

Write simplify_ratio(a, b) returning [a, b] divided by their greatest common divisor, so the ratio is reduced as far as it will go.

gcd
BuildA reproducible shuffle

Write seeded_shuffle(seed, items): seed the random module with seed, shuffle a copy of items (never the original list), and return the shuffled copy.

shuffleseed
BossSplit a total with a remainder

Write split_evenly(total, people) returning [share, leftover]: each person's whole-number share, and whatever is left over after splitting as evenly as possible.

floor
CapstoneDeal two random teams

Write seeded_team_picks(seed, players, team_size): seed the random module, shuffle a copy of players, and return [team_one, team_two] — the first team_size shuffled players, then the rest.

shuffleseed
Project context and further resources
seeded_dice_rolls.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
seeded_dice_rolls(seed, n) → listSeed the RNG, then roll n six-sided dice and return the results.
try:
returned
No app map for this section yet.
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.