How to Generate Random Integers Between 0 and 9 in Python

Created
Modified

Using randrange Method

The random.randrange(start, stop[, step]) method returns a randomly selected element from range(start, stop, step). For example,

#!/usr/bin/python3

# Import module
import random

print(random.randrange(10))
print(random.randrange(7, 10))
4
8

Using randint Method

The random.randint(a, b) method returns a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

#!/usr/bin/python3

# Import module
import random

print(random.randint(7, 10))

# uniform gives you a floating-point value
print(random.uniform(7, 10))
8
7.8336193746821445

It is faster to use the random module than the secrets module.

Using randbelow Method

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

To randomly print an integer in the inclusive range 0-9:

#!/usr/bin/python3

# Import module
import secrets

print(secrets.randbelow(10))
4

This is better than the random module for cryptography or security uses.

Related Tags