Menu

random.randint(low, high) returns a random whole number from a stated low value up to a stated high value. You can use it anywhere a program needs an unpredictable whole number, such as picking a shelf number, a seat number or a page to open.

Both ends are possible

The range of randint is inclusive at both ends. That means the low value and the high value are both possible results, as well as every whole number in between. Calling random.randint(3, 9) can give 3, 4, 5, 6, 7, 8 or 9, so there are seven possible answers.

A common slip is to assume randint stops one short of the high value, as range() does. It doesn't: the high value itself can be returned.

randint compared with range()

range() counts from its start value but stops before it reaches the end value, so the end value is never produced. randint behaves differently, and the table shows the effect of the same two numbers.

CallSmallest valueLargest valueEnd value included?
random.randint(3, 9)39Yes
range(3, 9)38No

So the numbers you would type into range() are not the numbers to use in randint for the same set of values. range(1, 9) counts 1 to 8, while random.randint(1, 9) can also return 9.

Worked example

A school library labels its shelves 3 to 9. To send a pupil to a random shelf, the low value is 3 and the high value is 9. Because both ends count, shelf 3 and shelf 9 are each just as possible as shelf 6, so no shelf is left out.

import random

shelf = random.randint(3, 9)
print("Collect your book from shelf", shelf)

Output:

Collect your book from shelf 9

Practise this