← Python lessons

Random Numbers in Python

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

random.randint(a, b) picks a random whole number from a to b, including both ends. It lives in Python's random module.

Import the random module

Write import random at the top of your program. Then put random. before each function you use from it.

import random

roll = random.randint(1, 6)
print(roll)

Press Run a few times. Each run prints a number from 1 to 6, and it can change every time.

Both ends are included

Unlike range(), randint includes its second number. random.randint(1, 100) can give 1, 100 or anything between.

import random

coin = random.randint(0, 1)
print(coin)

This prints 0 or 1.

Keep the number in a variable

Each call to randint picks a new number. Store the pick in a variable when you need the same number again later.

import random

secret = random.randint(1, 10)
print(secret == secret)
print(random.randint(1, 10) == random.randint(1, 10))

The first line is always True. The second is usually False, because it compares two different picks.

See also: Python Import, The range() Function.

Your turn

randint(low, high) can pick any whole number from low to high. Print how many different numbers that is, worked out from low and high.

low = 1
high = 6
# add one print: how many numbers randint(low, high) can pick

Expected output

6

Advanced reading

Practise this lesson

This exercise uses this lesson. It runs in your browser and checks your code instantly — no sign-up needed.

Python Fundamentals