Python: Generate a Random 6-Digit Number
In this article
Use random.randint(100000, 999999) to get a random six-digit number that never starts with zero, or f'{random.randint(0, 999999):06d}' when a leading zero is acceptable. If the number will act as a verification code, password-reset token or anything else a person could abuse, switch to the secrets module instead — random is built for simulations and games, and its output can be predicted if someone sees enough of it.
What You'll Need
- Python 3 installed (f-strings in the examples need 3.6 or newer). Check with
python3 --versionin a terminal, orpython --versionon Windows. - A way to run code: a plain text file saved as
six_digits.py, or an interactive Python prompt (REPL) for quick tests. - Nothing else.
randomandsecretsare both part of the standard library, so there is nothing to install.
Step-by-Step
- Open a terminal and confirm Python runs. Type
python3 --version. On macOS and Linux the correct command is oftenpython3rather thanpython; on Windows it is usuallypython, or thepylauncher. If you get a version number, you are ready. - Create a file for the script. Save it as
six_digits.pyin any folder you can find again, then open it in a text editor. Do not name the filerandom.py— see Troubleshooting for why. - Import the module at the top of the file. Add the line
import random. - Generate the basic six-digit number. Write
number = random.randint(100000, 999999)followed byprint(number).randintincludes both endpoints, so 100000 and 999999 are both possible results, and every result is exactly six digits with no leading zero. - Allow leading zeros if you need a fixed-width code. Replace the line with
code = f'{random.randint(0, 999999):06d}'. The:06dformat keeps six characters by padding the front with zeros, so 42 becomes000042. The result is a string, not an integer — that is intentional, because an integer cannot store a leading zero. An older alternative isstr(random.randint(0, 999999)).zfill(6). - Swap in
secretsif the code protects anything. Addimport secrets, then usecode = f'{secrets.randbelow(1_000_000):06d}'.randbelowexcludes its upper bound, so 1,000,000 gives you 0 to 999,999. The underscore in the number is just a readability separator and is valid in Python 3.6 and later. - Run the script and check the output. From the folder holding the file, run
python3 six_digits.py(orpython six_digits.pyon Windows). To see more than one result, wrap the generation line infor _ in range(10):and indent theprintbelow it. Every line should be six characters long.
Common Mistakes
- Using
randrange(100000, 999999)and missing the top value.randrangeexcludes its upper bound, so 999999 can never appear. Writerandrange(100000, 1000000)instead. - Expecting an integer to keep leading zeros.
int('000042')is 42. Keep fixed-width codes as strings all the way to the display layer and the database column. - Using
randomfor one-time codes. Therandommodule is a general-purpose generator, not a cryptographic one. Anything a user could profit from guessing belongs insecrets. - Assuming the numbers are unique. Each call is independent; repeats are normal and expected across a batch of a few hundred codes.
- Seeding with a fixed value. A line like
random.seed(42)makes every run produce the same sequence. Delete it unless you are deliberately reproducing a simulation. - Building the number by hand from
random.random().int(random.random() * 900000 + 100000)works but is easy to get wrong at the boundaries and returns a float until you cast it. The built-in functions are clearer and correct.
Tips
- Generate a batch in one line:
codes = [f'{random.randint(0, 999999):06d}' for _ in range(20)]. Change the number to change the batch size. - Guarantee no duplicates:
random.sample(range(100000, 1000000), k=20)returns 20 distinct numbers. Note that this is without replacement — once the pool shrinks, drawing more numbers than the pool allows raises an error. - Treat a six-digit code as a short-lived value, not a secret. Only one million combinations exist, so an exposed endpoint needs an expiry time and a limit on failed attempts to be safe.
- Keep codes out of logs and error messages. Log the fact that a code was issued, not the code itself.
Troubleshooting
- The script errors with
ModuleNotFoundError: No module named 'random'. You almost certainly saved your own file asrandom.py, which shadows the standard library module. Rename your file, delete anyrandom.pycleft beside it, and run again. python: command not foundorpython3: command not found. Try the other spelling first. If neither works, Python is not on your PATH and needs reinstalling from the official installer.- Every run prints the same number. A fixed seed is still in the file, or you are re-running a saved output instead of the script. Remove the
random.seed(...)call. - The leading zeros keep disappearing. Something is converting the code to an integer, either an explicit
int()call or an integer database column. Format the value with:06donly at the moment you display or store it. - Some outputs look shorter than six digits. You are using
random.randint(0, 999999)without the:06dformat, which is correct behaviour — that range includes values below 100000. - Two codes in a batch match. That is not a bug. Use
random.sampleif uniqueness is a requirement.
Frequently Asked Questions
Does randint(100000, 999999) ever return a five-digit number?
No. Both bounds are inclusive, and the lower bound is 100000, so every result is exactly six digits and never begins with zero.
How do I get a six-digit string that may start with 0?
Generate from 0 to 999999 and format it: f'{random.randint(0, 999999):06d}'. The result is a string with exactly six characters.
Is random safe for a verification code or password reset?
No. Use secrets.randbelow instead. The secrets module draws from the operating system's cryptographic random source, which is the appropriate tool for anything security-related.
How do I generate several six-digit numbers at once?
Use a list comprehension: [random.randint(100000, 999999) for _ in range(10)]. That returns a list of ten independent numbers.
How do I avoid duplicate codes?
Use random.sample(range(100000, 1000000), k=10), which draws without replacement. For cryptographically strong unique values, generate with secrets and check against a set of codes you have already issued.
Do I need to install anything?
No. random and secrets ship with every standard Python 3 installation, so there is no package to add.