Data types · 9 / 29 Theory

Random numbers with random

Games, simulations and tests often need random values. Python provides them in the random module, which is part of the standard library: nothing to install, just import it.

A random integer: randint

random.randint(a, b) returns an integer between a and b, both included:

import random

die = random.randint(1, 6)
print(die)   # a number from 1 to 6, different on each run

The two limits must be in order: random.randint(5, 1) raises a ValueError.

A random decimal

import random

print(random.random())        # between 0 and 1 (never reaching 1)
print(random.uniform(2, 3))   # a decimal between 2 and 3

Choosing and shuffling

import random

colors = ["red", "green", "blue"]
print(random.choice(colors))   # one of the three

numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)        # shuffles the list in place
print(numbers)                 # for example [3, 1, 5, 2, 4]

Repeatable results: seed

"Random" numbers are generated by a formula from an initial value called the seed. If you set the seed with random.seed(value), the sequence is always the same. It is very useful for debugging:

import random

random.seed(42)
first = random.randint(1, 100)

random.seed(42)
second = random.randint(1, 100)

print(first == second)   # True

Testing programs that use randomness

Since the result changes on every run, it cannot be compared with a fixed output. One way to test them is to use cases where randomness has no room: random.randint(5, 5) can only give 5. Another is to check that the value is within the expected range.

Combining it with what you have learned

import random

minimum = int(input())
maximum = int(input())
print(random.randint(minimum, maximum))

Practice in the exercise about generating a random number.