Python random Module for Games

The Python random module for games: random numbers with randint, picking with choice, shuffling, sampling without repeats, and seeds for repeatable results.

Randomness makes games replayable: a different secret number, a new word, ships in new places. Start with import random, then use these functions.

example 1 · press Run, then edit and run again

Which one should I use?

Seeds: the same "random" every time

random.seed(42) makes the sequence repeat exactly. That's useful for testing a game, or for a "daily puzzle" that's the same for everyone.

example 2 · press Run, then edit and run again

💡 randint(1, 10) includes 10, but randrange(1, 10) stops at 9. Mixing them up is a common bug.

Games that use The random module

Practise this with 17 of the 20 games:

Frequently asked questions

How do I get a random number in Python?

import random, then random.randint(1, 100) for a whole number from 1 to 100, or random.random() for a decimal from 0 to 1.

How do I pick a random item without repeats?

Use random.sample(items, k) to get k different items, or shuffle the list and take items from the front.

More Python concepts