Use random.randint(0, 9) or random.randrange(10) from Python’s built-in random module to generate a random integer between 0 and 9 (both inclusive).
Basic Example
import random
# 1. Inclusive on both ends: generates an integer from 0 through 9
num1 = random.randint(0, 9)
# 2. Half-open range (like range()): stops before 10, so generates 0 through 9
num2 = random.randrange(10)
print(num1, num2) # Example Output: 4 7
Key Details & Alternatives
random.randint(a, b)vs.random.randrange(stop): Both endpointsaandbare inclusive inrandint(0, 9), whereasrandrange(10)excludes10(matching Python’s built-inrange()behavior).- Cryptographically secure integers (
secrets): Therandommodule uses the Mersenne Twister algorithm, which is predictable and unsuitable for passwords, OTPs, or security tokens. For security-sensitive tasks, usesecrets.randbelow(10)instead:import secrets secure_digit = secrets.randbelow(10) # Cryptographically secure integer from 0 to 9 - Generating multiple random integers at once: Use
random.choices()(with replacement) orrandom.sample()(without replacement) rather than callingrandint()inside a loop:# 5 random digits from 0–9 (duplicates allowed) digits = random.choices(range(10), k=5) # 5 unique random digits from 0–9 (no duplicates) unique_digits = random.sample(range(10), k=5) - Vectorized arrays (
NumPy): For data science or large arrays, usenp.random.default_rng().integers(0, 10, size=5)(note that the upper bound10is exclusive).
Comparison of Methods
| Function | Upper Bound (9 vs. 10) |
Cryptographically Secure? | Best Used When |
|---|---|---|---|
random.randint(0, 9) |
Inclusive (9) |
No | General-purpose single random integer. |
random.randrange(10) |
Exclusive (10) |
No | Matching range() indexing or adding a step. |
secrets.randbelow(10) |
Exclusive (10) |
Yes | PINs, OTP codes, passwords, and tokens. |
random.choices(range(10), k=n) |
Exclusive (10) |
No | Generating a list of n random integers quickly. |
You must log in or register to comment.
