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.
Which one should I use?
- randint(a, b): a whole number from a to b. Secret numbers, damage, steps.
- choice(list): one item. The computer's move, a random word.
- shuffle(list): reorders a list in place. Quiz questions.
- sample(items, k): k different items. Mine positions, typing lines.
- randrange(n): 0 to n - 1, handy for list positions.
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.
💡 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:
- #01☆☆☆
Tic Tac Toe in Python
Learn Lists, Functions and if, elif and else.
- #02☆☆☆
Rock Paper Scissors in Python
Learn The random module, Dictionaries and if, elif and else.
- #04☆☆☆
Hangman in Python
Learn Strings, Lists and while loops.
- #05☆☆☆
Number Guessing Game in Python
Learn The random module, while loops and if, elif and else.
- #07☆☆☆
Mad Libs-Style Story Game in Python
Learn input() and print(), Strings and Variables.
- #09☆☆☆
Connect Four-Style Game in Python
Learn 2D lists and grids, Lists and Functions.
- #10☆☆☆
Minesweeper-Style Game in Python
Learn 2D lists and grids, Functions and for loops.
- #11☆☆☆
Sudoku in Python
Learn 2D lists and grids, Functions and for loops.
- #12☆☆☆
Battleship-Style Game in Python
Learn 2D lists and grids, The random module and Strings.
- #13☆☆☆
Maze Game in Python
Learn 2D lists and grids, Functions and Lists.
- #14☆☆☆
Higher or Lower Game in Python
Learn The random module, while loops and if, elif and else.
- #15☆☆☆
Word Guessing Game in Python
Learn Strings, Lists and Dictionaries.
- #16☆☆☆
Coin Flip in Python
Learn The random module, for loops and Variables.
- #17☆☆☆
Turtle Race in Python
Learn Turtle graphics, Lists and for loops.
- #18☆☆☆
Python Quiz Game
Learn Dictionaries, Lists and for loops.
- #19☆☆☆
Math Quiz Game in Python
Learn The random module, Dictionaries and for loops.
- #20☆☆☆
Typing Speed Game in Python
Learn Strings, Functions and for loops.
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.