Python Arena
Step 1 of 3

Random whole numbers

Games, simulations and quizzes need numbers nobody can predict: the roll of a die, the next card, the order of the questions. The standard library's random module makes them.

randint

random.randint(a, b) gives a random whole number from a to b. This program rolls a die five times:

import random

random.seed(2026)
for i in range(5):
    print("You rolled", random.randint(1, 6))
Output
You rolled 1
You rolled 3
You rolled 5
You rolled 5
You rolled 6

What about the line random.seed(2026)? It makes the program pick the same "random" numbers on every run, so the output shown here is what you'll see when you run it too. Every example in these lessons that uses random numbers starts with such a line, and step 3 of this module explains how it works. Leave it out, and the numbers change on every run, which is what a real game wants.

Both ends included

Unlike range(1, 6), which stops before 6, randint(1, 6) can give 1 and 6 and everything between. Roll a thousand times and both ends turn up:

import random

random.seed(1)
rolls = []
for i in range(1000):
    rolls.append(random.randint(1, 6))
print("Smallest:", min(rolls))
print("Largest:", max(rolls))
Output
Smallest: 1
Largest: 6

Using the number

A random number is an ordinary integer, so it works in calculations and conditions like any other. Here randint(0, 1) tosses a coin, and the functions come in with from, as in the previous module:

from random import randint, seed

seed(7)
for i in range(4):
    if randint(0, 1) == 0:
        print("Heads")
    else:
        print("Tails")
Output
Tails
Heads
Tails
Heads

One call, one number

Every call of randint gives a new number, but a variable keeps the one it was given. This program rolls the die once and prints that same roll three times:

import random

random.seed(3)
roll = random.randint(1, 6)
for i in range(3):
    print(roll)
Output
2
2
2

For three different rolls, call random.randint(1, 6) inside the loop, once for each roll.

Your task

Challenge 1 of 3

Fill in the blanks so the program rolls a 20-sided die (the numbers 1 to 20) three times.

Challenge 2

Write a function roll_dice(count) that rolls a six-sided die count times with randint and returns the rolls in a list, in the order they were rolled.

The checks set the seed themselves, so leave random.seed out of the function.

Challenge 3

Write a number guessing game. The program first asks for a game number and passes it to random.seed, so the same game number always gives the same secret number (handy for testing, and for challenging a friend to the very same game). Then it picks the secret number with random.randint(1, 100) and asks for guesses until the player finds it. It answers each wrong guess with Too small or Too big, and the right one with Correct! and the number of guesses. For example:

Game number: 1
Guess: 50
Too big
Guess: 25
Too big
Guess: 12
Too small
Guess: 18
Correct! Guesses: 4