How do you generate random integers between 0 and 9 in Python? | A1Lab@MZeeshanM to PythonEnglish • 7 days ago

How do you generate random integers between 0 and 9 in Python?

message-square
0

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 endpoints a and b are inclusive in randint(0, 9), whereas randrange(10) excludes 10 (matching Python’s built-in range() behavior).
  • Cryptographically secure integers (secrets): The random module uses the Mersenne Twister algorithm, which is predictable and unsuitable for passwords, OTPs, or security tokens. For security-sensitive tasks, use secrets.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) or random.sample() (without replacement) rather than calling randint() 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, use np.random.default_rng().integers(0, 10, size=5) (note that the upper bound 10 is 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.