Making Random Numbers

Python contains lots of tools to generate randomness. To use randomness in the Python Shell, you should first type import random at the top of your file. This is a library, or expansion for Python that will include many useful methods for using randomness.

>>> import random

>>>

The first function from random we'll talk about is called randint. randint lets you generate integers, or whole numbers, between a minimum and maximum value.

random.randint(min, max) is used to select a random integer between the two values, including the min and max. For example, random.randint(1,5) will select either 1, 2, 3, 4 or 5.

>>> random.randint(1, 5)

3

>>> random.randint(1, 5)

5

>>> random.randint(1, 5)

2

But what happens when the minimum number is equal to the maximum number? For example, when you run random.randint(3,3)?

>>> random.randint(3, 3)

3

>>> random.randint(3, 3)

3

>>> random.randint(3, 3)

3

This will return 3 no matter how many times you run it, since this is the only integer in this range.

The maximum must always be above the minimum, otherwise the program will return an error.

>>> random.randint(3, 1)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "/usr/local/lib/python3.9/random.py", line 339, in randint

return self.randrange(a, b+1)

File "/usr/local/lib/python3.9/random.py", line 317, in randrange

raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))

ValueError: empty range for randrange() (3, 2, -1)

random.randint(3,1) will always crash since 3 is larger than 1.

Another, similar function is called random - just like the name of the library.

Calling random.random() will return a random number between 0 and 1.

>>> random.random()

0.00189375771289

>>> random.random()

0.07708434707270495

>>> random.random()

0.23899179514972158

This function must not be passed any arguments, so random.random(2) or random.random(“Hello!”) will both cause errors.