Random 6 Digit Number in Python: How-To
In this article
Use Python's built-in secrets module to create a random 6-digit number: import secrets; code = secrets.randbelow(900000) + 100000. That single line returns an integer between 100000 and 999999, which is exactly six digits with no leading zero. If you specifically want a string that may start with a zero (like "042317"), use ''.join(secrets.choice('0123456789') for _ in range(6)) instead. The older random module also works for non-security uses, and the steps below cover both, plus how to format the result, avoid the common off-by-one traps, and test that your output really is six digits every time.
What You'll Need
- Python 3.6 or newer installed (the
secretsmodule was added in 3.6). Runpython --versionorpython3 --versionto check. - A way to run Python: the interactive interpreter, a
.pyscript, or an editor such as IDLE or VS Code. - No third-party packages. Everything below uses the standard library only, so there is nothing to
pip install.
Step-by-Step
- Decide what "6-digit number" means for your case. There are two common interpretations. A numeric value from 100000 to 999999 (never starts with zero) is what you want for IDs, PINs, or anything stored as an integer. A six-character digit string from
000000to999999(leading zeros allowed) is what you want for one-time codes displayed to a user. Pick one before you write code, because the two need different approaches. - For a true numeric value, use
secrets. Open a script or the interpreter and write:import secrets code = secrets.randbelow(900000) + 100000 print(code)randbelow(900000)returns an integer from 0 to 899999. Adding 100000 shifts that range to 100000 through 999999, so the result is always six digits. Run it a few times to confirm the output length never drops to five digits. - For a six-character code with possible leading zeros, use
secrets.choice. Write:
This picks six characters independently, soimport secrets code = ''.join(secrets.choice('0123456789') for _ in range(6)) print(code)000042is a valid outcome. If you need it as an integer later, convert withint(code), but remember that conversion drops the leading zeros. - Use
randomonly when security does not matter. For simulations, test data, or a quick dice-style pick, therandommodule is fine:import random code = random.randint(100000, 999999)randintincludes both endpoints, so 999999 is reachable. Do not userandomfor passwords, verification codes, or anything an attacker could benefit from predicting; its output is not cryptographically secure. Usesecretsfor those. - Format the number as a zero-padded string if you need a fixed width. If you already have an integer and want exactly six characters, use an f-string:
This printscode = 4231 print(f'{code:06d}')004231. The06dmeans "pad with zeros to a total width of six digits." This is the cleanest way to turn any small integer into a six-digit display string. - Wrap it in a reusable function. Put the logic in one place so you can call it from anywhere:
Returning a string version is often more practical: change the return line toimport secrets def six_digit_code(): return secrets.randbelow(900000) + 100000 print(six_digit_code())return str(secrets.randbelow(900000) + 100000)so callers do not have to convert. - Test the boundaries. Run a loop of a few thousand iterations and check the minimum and maximum values, plus the length of every result:
The last line should printresults = [six_digit_code() for _ in range(10000)] print(min(results), max(results)) print(all(100000 <= r <= 999999 for r in results))True. If it printsFalse, your range arithmetic is off by one somewhere. - Store or display the result safely. If the code is a verification or access code, do not log it in plain text, do not print it to a shared console in production, and do not reuse it. Generate a fresh one per request and expire it after a short window. If you are storing it, hash it the same way you would a password rather than keeping the raw digits.
Common Mistakes
- Using
random.randint(0, 999999)and expecting six digits. This returns values from 0 upward, so you get7,482, or51023just as often as a six-digit number. Either raise the lower bound to 100000 or zero-pad the output. - Off-by-one in the range.
randbelow(1000000)gives 0 to 999999, not 100000 to 999999.randbelow(900000) + 100000is the correct shift for the six-digit range. - Assuming
randintexcludes the upper bound. It includes it.randrangeexcludes it. Mixing the two up silently changes your range. - Using
randomfor security-sensitive codes. Therandommodule is a pseudo-random generator seeded predictably enough that it should not guard accounts or money. Usesecrets. - Converting a zero-padded string back to an int too early.
int('004231')becomes4231, and the display loses its width. Keep it as a string until you genuinely need arithmetic. - Seeding with the clock or a fixed value.
random.seed(0)makes output repeatable, which is useful for tests and dangerous for real codes.
Tips
- Prefer
secretsby default. It costs nothing extra and removes a whole class of mistakes if the code later turns out to be security-relevant. - Use
secrets.token_hex(3)if you want six random hex characters instead of six decimal digits; it is shorter to write and equally secure. - For a batch of codes, a list comprehension is readable:
[six_digit_code() for _ in range(10)]. - If codes must be unique across a system, randomness alone is not enough. Check against your database or use a UUID and derive the digits from it.
- Keep the generation logic in one function so you can swap the algorithm later without hunting through the codebase.
Troubleshooting
ModuleNotFoundError: No module named 'secrets'means you are on Python 3.5 or older. Check withpython --versionand upgrade to a current Python 3 release.- Output sometimes has fewer than six digits means you used a lower bound of 0 or 1. Change it to 100000, or apply the
:06dformat. - Output is the same every run means something is seeding the generator with a fixed value, or you are calling a cached result. Remove any
seed()call and make sure the function is actually invoked each time. - Leading zeros disappear means the value passed through an integer conversion or a database column typed as an integer. Store it as text, or pad on display with
f'{value:06d}'. - Codes collide more than expected is normal for small spaces over time. With a million possible values, collisions become likely after a few thousand issued codes. Add a uniqueness check if that matters.
Frequently Asked Questions
What is the difference between random and secrets?
random is a fast pseudo-random generator meant for simulations and games. secrets draws from the operating system's cryptographically secure source and is the right choice for codes, tokens, and passwords.
How do I get exactly six digits including leading zeros?
Build a string with ''.join(secrets.choice('0123456789') for _ in range(6)), or pad an integer with f'{n:06d}'.
Can I use uuid instead?
Yes, but a UUID is 128 bits and far longer than six digits. You can take digits from it, but you lose the uniqueness guarantee once you truncate, so check for collisions.
Is randint(100000, 999999) inclusive of both ends?
Yes. randint includes both endpoints, so 100000 and 999999 are both possible results.
How do I make the code reproducible for tests?
Use random.seed(42) with the random module in tests only. Never seed secrets; it has no seed function by design.