Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python: Generate a Random 6-Digit Number

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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 --version in a terminal, or python --version on 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. random and secrets are both part of the standard library, so there is nothing to install.

Step-by-Step

  1. Open a terminal and confirm Python runs. Type python3 --version. On macOS and Linux the correct command is often python3 rather than python; on Windows it is usually python, or the py launcher. If you get a version number, you are ready.
  2. Create a file for the script. Save it as six_digits.py in any folder you can find again, then open it in a text editor. Do not name the file random.py — see Troubleshooting for why.
  3. Import the module at the top of the file. Add the line import random.
  4. Generate the basic six-digit number. Write number = random.randint(100000, 999999) followed by print(number). randint includes both endpoints, so 100000 and 999999 are both possible results, and every result is exactly six digits with no leading zero.
  5. Allow leading zeros if you need a fixed-width code. Replace the line with code = f'{random.randint(0, 999999):06d}'. The :06d format keeps six characters by padding the front with zeros, so 42 becomes 000042. The result is a string, not an integer — that is intentional, because an integer cannot store a leading zero. An older alternative is str(random.randint(0, 999999)).zfill(6).
  6. Swap in secrets if the code protects anything. Add import secrets, then use code = f'{secrets.randbelow(1_000_000):06d}'. randbelow excludes 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.
  7. Run the script and check the output. From the folder holding the file, run python3 six_digits.py (or python six_digits.py on Windows). To see more than one result, wrap the generation line in for _ in range(10): and indent the print below it. Every line should be six characters long.

Common Mistakes

  • Using randrange(100000, 999999) and missing the top value. randrange excludes its upper bound, so 999999 can never appear. Write randrange(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 random for one-time codes. The random module is a general-purpose generator, not a cryptographic one. Anything a user could profit from guessing belongs in secrets.
  • 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 as random.py, which shadows the standard library module. Rename your file, delete any random.pyc left beside it, and run again.
  • python: command not found or python3: 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 :06d only at the moment you display or store it.
  • Some outputs look shorter than six digits. You are using random.randint(0, 999999) without the :06d format, which is correct behaviour — that range includes values below 100000.
  • Two codes in a batch match. That is not a bug. Use random.sample if 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.