🎓 A1Learner
🔍
0 of 116 lessons completed

Python Random Module

The random module makes numbers and picks that look unplanned. A seed can fix the pattern so the same results repeat.

Roll a die twice

First we fix the seed. Then both rolls repeat on every run.

import random

random.seed(42)
print(random.randint(1, 6))
print(random.randint(1, 6))

Pick one item

choice() picks one item from a list.

import random

random.seed(42)
print(random.choice(["red", "green", "blue"]))

Shuffle a list

shuffle() mixes a list in place. The list itself changes.

import random

random.seed(42)
cards = [10, 20, 30, 40]
random.shuffle(cards)
print(cards)

A random float

random() gives a float from 0.0 up to 1.0. The value is never 1.0.

import random

random.seed(42)
print(random.random())

Example

import random

random.seed(99)
for i in range(1, 4):
    print(f"Roll {i}: {random.randint(1, 6)}")

Key points

  • Use import random to use the random module
  • The random module is a ready module for chance-based picks and numbers.
  • Use random.randint() to pick a whole number in a range
  • Use random.choice() to pick one item from a list
  • Use random.seed() to fix where the random pattern starts

In this example, the seed is fixed at 99. The loop runs three times, for rolls 1 to 3. Each round prints one randint() roll from 1 to 6. Because the seed is fixed, the rolls are 4, 4, and 2. They are the same on every run.

Note

With the same seed, the same results repeat each run.

Real games leave the seed out, so each run differs.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Why does this lesson set a seed before rolling?