22. Randomness

The random module is useful for games, simple simulations, sampling, and shuffling. It gives you common tools for making non-deterministic choices.

22.1. Random numbers

Use randint() when you want a random integer in a closed range.

1from random import randint, random
2
3print(random())
4print(randint(1, 6))
5print(randint(1, 100))

22.2. Picking values

Use choice() for a single random element and sample() for multiple unique values.

1from random import choice, sample
2
3names = ['Ava', 'Noah', 'Mia', 'Luca', 'Emma']
4
5print(choice(names))
6print(sample(names, 3))

22.3. Shuffling data

Use shuffle() when you want to rearrange a list in place.

1from random import shuffle
2
3cards = ['A', 'K', 'Q', 'J', '10']
4shuffle(cards)
5print(cards)

22.4. Exercise

Simulate rolling two dice 1,000 times. Count how often each total from 2 through 12 appears.

22.4.1. Solution

1from collections import Counter
2from random import randint
3
4counts = Counter()
5for _ in range(1000):
6    total = randint(1, 6) + randint(1, 6)
7    counts[total] += 1
8
9print(counts)