To generate a 5-digit random number in Python, use random.randint(10000, 99999) for a uniform integer, or random.randrange(10000, 100000) for the same range. If you need a string with leading zeros (e.g., “01234”), use str(random.randint(0, 99999)).zfill(5) or f"{random.randint(0, 99999):05d}". For security-sensitive uses (passwords, tokens), use secrets.randbelow(90000) + 10000 instead of the random module.
Why the Range Matters
A 5-digit number is any integer from 10000 to 99999 inclusive. That’s 90,000 possible values. The lower bound is 10000 because a number like 09999 is not a 5-digit number in the mathematical sense—it’s a 4-digit number with a leading zero. If you include 00000 through 09999, you get 100,000 values, but many people mean the 90,000 range when they say “5-digit.” Choose based on your need:
- True 5-digit integer: 10000–99999 (90,000 values)
- 5-character string with leading zeros: 00000–99999 (100,000 values)
The random.randint(a, b) function returns an integer N such that a ≤ N ≤ b, inclusive on both ends. So random.randint(10000, 99999) gives exactly the true 5-digit range.
How random.randint Works
Python’s random module uses the Mersenne Twister algorithm, a pseudorandom number generator (PRNG). It’s deterministic: given the same seed, it produces the same sequence. That’s fine for simulations, games, or any non-security purpose. The function randint is a convenience wrapper around randrange, which itself uses _randbelow to get a uniform value. The distribution is approximately uniform across the range, meaning each of the 90,000 numbers has roughly the same chance of appearing.
Example:
import random
print(random.randint(10000, 99999)) # e.g., 48372
If you need a list of 5 such numbers:
numbers = [random.randint(10000, 99999) for _ in range(5)]
Using random.randrange and random.choice
random.randrange(start, stop) excludes the stop value. So to get 10000–99999, use random.randrange(10000, 100000). This is equivalent to randint(10000, 99999).
Alternatively, you can build a 5-digit number by choosing each digit separately with random.choice:
import random
first = random.choice('123456789') # first digit cannot be 0
digits = [random.choice('0123456789') for _ in range(4)]
num_str = first + ''.join(digits)
num = int(num_str)
This method is more flexible if you want to enforce patterns (like no repeated digits), but it’s slower and more code. For most cases, randint is simpler.
Generating a 5-Digit String with Leading Zeros
Sometimes you need a fixed-width string, like an OTP or an ID, where “00123” is valid. Use string formatting:
import random
num = random.randint(0, 99999)
code = f"{num:05d}" # '00123'
Or with zfill:
code = str(random.randint(0, 99999)).zfill(5)
Both produce a 5-character string with leading zeros. Note that randint(0, 99999) includes 00000, so you get all 100,000 combinations.
Security: Use secrets Instead of random
The random module is not cryptographically secure. An attacker who observes a few outputs can potentially predict future numbers because the Mersenne Twister’s state can be reconstructed. For any security-related application—password reset tokens, OTPs, lottery draws, or encryption keys—use Python’s secrets module, which draws from the operating system’s secure random source.
import secrets
secure_num = secrets.randbelow(90000) + 10000 # 10000-99999
For a string with leading zeros:
secure_code = f"{secrets.randbelow(100000):05d}"
Always prefer secrets when the number is used for authentication or authorization. The random module is fine for non-security uses like games or sampling.
Common Pitfalls and Misconceptions
One common mistake is using random.random() (which returns a float between 0 and 1) and multiplying by 100000, then converting to int. That can give numbers like 99999, but it’s unnecessarily complex and can introduce off-by-one errors. Stick with randint.
Another pitfall: forgetting that randrange excludes the stop. random.randrange(10000, 99999) actually gives 10000–99998, missing 99999. Use 100000 as the stop.
Also, be aware that random.randint(0, 99999) includes 0, which is not a 5-digit number. If you need a true 5-digit integer, start at 10000.
Finally, don’t use random.seed() with a fixed value in production unless you intentionally want reproducible results (e.g., for testing). A fixed seed means the same sequence every run, which might surprise users.
Performance and Alternatives
Generating a single random number is extremely fast—microseconds. If you need millions, random.randint is still fine, but you can use NumPy for vectorized generation:
import numpy as np
arr = np.random.randint(10000, 100000, size=10) # array of 10
NumPy’s generator is also Mersenne Twister, but it’s faster for bulk operations. For cryptographic security at scale, use secrets per number, as it’s slower but secure.
If you need a unique 5-digit number (like an ID), beware: random doesn’t guarantee uniqueness. To avoid duplicates, track used numbers or use a counter. For a large set, consider using a database auto-increment or a UUID.
Frequently Asked Questions
How do I generate a random 5-digit number in Python without repeating digits?
Use random.sample to pick 5 distinct digits, then arrange them. Ensure the first digit isn’t 0:
import random
digits = random.sample('0123456789', 5)
if digits[0] == '0':
digits[0], digits[1] = digits[1], digits[0]
num = int(''.join(digits))
This gives a 5-digit number with all digits unique, though the first digit swap might make a leading zero after the swap? Actually, after swapping, the first digit is non-zero because the original first was 0 and the second was non-zero (since sample gives distinct digits, the second is not 0). So it works.
What’s the difference between random.randint and random.randrange?
randint(a, b) is inclusive of both endpoints. randrange(a, b) is exclusive of b. So randrange(10000, 100000) is the same as randint(10000, 99999). Use whichever is clearer to you.
Can I generate a 5-digit number with a specific seed for reproducibility?
Yes: call random.seed(42) before generating. That makes the sequence repeatable, which is useful for debugging or demos. But don’t use a fixed seed in production if you want unpredictability.
Is random.randint truly random?
No, it’s pseudorandom. It’s deterministic and predictable if you know the seed and the algorithm. For most non-security purposes, it’s random enough. For security, use secrets.
How do I generate a random 5-digit number in a range like 20000-80000?
Use random.randint(20000, 80000). The same pattern works for any range: random.randint(lower, upper). For a string with leading zeros in that range, use f"{random.randint(20000, 80000):05d}"—though that will never have leading zeros since the lower bound is 20000.
Why does my code sometimes produce a 4-digit number?
If you use random.randint(0, 99999) and treat the integer as a number, values below 10000 are 4-digit or fewer. To always get a 5-digit integer, use randint(10000, 99999). If you need a string, use zero-padding.
Related
- Auto Sum Shortcut in Excel: Quick Keys & Steps
- Computer Data Entry Job Vacancy: Real Answers
- How to Select a Cell and Everything Below It in Excel
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Dotted Line in Excel and Word: How to Add OneTo add a dotted line at the bottom of a cell or selected range in Excel, select it,…
- Excel Average Keyboard Shortcut and Fastest MethodsExcel does not have a single, dedicated keyboard shortcut that inserts an average formula in every situation. In…
- Excel Not Letting You Copy and Paste? Fixes That WorkIf Excel will not copy and paste, first press Esc, select one ordinary cell, copy it with Ctrl+C,…
- Google Sheets Habit Tracker: Build One That WorksA Google Sheets habit tracker is a spreadsheet for recording whether you completed habits on particular days; the…
- Excel Data Validation List Autocomplete: How It WorksIn an up-to-date Microsoft 365 version of Excel, a data-validation dropdown can autocomplete by filtering its choices as…
- Google Sheets Can’t Open Apps Script? Fixes That WorkYes—Google Sheets can open Apps Script in a web browser: open the spreadsheet and choose Extensions > Apps…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.