A while ago I decided to build a password generator just to practice some Python. I fired up the editor, put together a script with the random module, and it worked great: if you give it a length, it spits out a string of characters.

Later, I found out that using random for anything that needs to be secure is a really bad idea. So, in this tutorial I’m going to show you why that module is unsuitable for security, and how to make a proper secure password generator with the secrets module instead.

So, this isn’t just another “here’s a password generator” tutorial. By the end, you'll know how to write a secure Python script, handle user input gracefully, and understand why standard random number generators aren't safe for passwords.

What We'll Cover:

How Most Beginners Write It and Mess it Up

This is what I (and pretty much every beginner) starts with:

import random
import string

chars = string.ascii_letters + string.digits
password = ''.join(random.choice(chars) for _ in range(12))
print(password)

It looks and runs fine. The passwords even look ok. The problem is that random is a pseudo-random number generator. It’s driven by a mathematical formula and a seed. If someone knows (or can guess) the seed, or sees enough outputs, the sequence becomes predictable.

For tasks like shuffling a playlist or rolling dice in a game, this is perfectly fine. But for passwords, it introduces a major security risk.

I used to think “random is random,” but apparently there’s a difference between “looks random” and “actually unpredictable.” I learned this lesson the hard way!

How to Use the Secrets Module for True Randomness

Python has a built-in module called secrets that’s made exactly for this kind of thing. Instead of relying on some predictable math formula, it pulls randomness straight from your operating system’s entropy source.

On Linux it grabs data from /dev/urandom, and on Windows it uses CryptGenRandom. Sounds a bit technical, but basically it just means it’s using the computer’s deepest, most secure source of randomness. That’s the standard way to handle passwords and security tokens in Python.

Here’s the basic secure version:

import secrets
import string

letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation

all_chars = letters + digits + symbols

password = ''.join(secrets.choice(all_chars) for _ in range(16))
print(password)

The code is almost identical. The only real change is swapping random for secrets. That one swap is the entire point of this whole thing.

How to Make it Interactive with the User Input

Instead of hard-coding the length, let’s just ask the user for it. People might type letters or symbols by accident instead of a number, so we’ll throw in some error handling, so the script doesn’t crash.

import secrets
import string

print("===== SECURE PASSWORD GENERATOR =====")

while True:
    try:
        length = int(input("\nHow long should the password be? (minimum 8): "))
        if length >= 8:
            break
        print("The Password must be at least 8 characters")
    except ValueError:
        print("Invalid Input. Please enter a number.")

all_chars = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(all_chars) for _ in range(length))

print(f"\nYour secure password is:{password}")

A few quick notes on what’s going on here:

  • The while True loop just keeps asking until it gets something usable.
  • The try/except block catches invalid inputs (like typing words instead of a number) so the script doesn't crash.
  • I set a minimum length of 8 characters because shorter passwords are easily compromised.

Save it as password_gen.py, run it with the python password_gen.py command, and you’re done. Try typing letters or a number under 8 to see if the error handling actually works. It’s oddly satisfying.

===== SECURE PASSWORD GENERATOR =====

How long should the password be? (minimum 8): 16

Here you go: k#P9$m!vQ2x@L8wE

What I Learned About Secure Code

One thing that still catches people is assuming that if the code runs and produces something that looks like a strong password, it must be fine. The first version I wrote ran perfectly and was still the wrong tool for the job. secrets is the one you want when the output needs to be hard to guess.

If you want to take it a bit further, you can force the password to include at least one number and one symbol, so it never comes out as pure letters. Or you can wrap it in a tiny GUI if you’re into that. I usually just keep the terminal version because it’s fast and I don’t have to think about it.

In summary, the main takeaway is to avoid the random module when building anything security-related. By switching to secrets and adding basic error handling for user input, you can create a script that is both secure and reliable. Now you have a tool you can actually trust to generate strong passwords.