Imports, math & random

Standard Library Tour, lesson 1 of 6

🧰 Standard Library Tour, lesson 1 of 6

Imports, math & random

Load modules three ways, compare floats safely and roll seeded dice.

11 min

2 exercises

1 quiz

0/3 solved

Getting Python ready… examples can run in a moment.

Python ships with a huge standard library: modules for math, dates, data formats, text and more, all available offline. Load one with import:

import math              # math.sqrt(16)
from math import sqrt    # sqrt(16)
import statistics as st  # st.mean([1, 2])

import module keeps it obvious where a name comes from. from module import name is handy for a few names you use a lot. Avoid from module import *: it dumps dozens of names into your code and can overwrite your own variables.

Example

Three ways to import

Add print(dir(math)) to list everything inside the math module.

Example

Comparing floats safely

Try 0.5 + 0.25 == 0.75. Why does that one work? (Halves and quarters are exact in binary.)

Quiz

What does this print?

Exercise

Distance between two points

Write distance(p, q) for two points given as (x, y) tuples. Use the Pythagorean theorem: √((x2 − x1)² + (y2 − y1)²).

random: controlled chaos. Handy tools:

  • random.randint(1, 6): whole number, both ends included
  • random.choice(seq): one random item
  • random.shuffle(lst): shuffles a list in place
  • random.sample(seq, k): k different items
  • random.random(): a float from 0 up to 1

Seeds. "Random" numbers come from a formula. random.seed(42) resets it to a known start, so you get the same sequence every run. Perfect for testing and replayable games.

Example

Rolling dice

Run it twice: same numbers, thanks to the seed. Change the seed, or delete the random.seed(7) line to get different rolls every run.

Example

Shuffle and sample

shuffle changes the list and returns None, so never write players = random.shuffle(players).

Exercise

Replayable dice

Write roll_dice(n, seed): seed the generator with seed, then return a list of n rolls made with random.randint(1, 6). The same seed must always give the same rolls.