← Intro to programming with Python

Randomness: the random module

Roll dice, shuffle and pick at random.

Start this lesson

Games and simulations need surprises. The random module gives you them: random.randint(1, 6) gives a whole number from 1 to 6 (both ends included, unlike range), random.choice(my_list) picks one item, and random.shuffle(my_list) mixes a list in place. Computers actually make "pseudo-random" numbers from a starting value called a seed. random.seed(5) fixes that start, so the same "random" results come out every time, which is very useful for testing.

import random

roll = random.randint(1, 6)
print("You rolled", roll)
snack = random.choice(["apple", "nuts", "yogurt"])
print("Today's snack:", snack)

random.seed(42)
print(random.randint(1, 100))   # the same number every run

Without a seed, each run gives different results. With random.seed(42) before it, the sequence repeats exactly.

Common mistake: expecting randint(1, 6) to stop before 6 the way range does. randint includes BOTH ends.

Another: writing my_list = random.shuffle(my_list). shuffle changes the list in place and returns None, just like sort.

To test a random program, check that results are in the right RANGE rather than equal to one exact value.