Home / Python / Example programs / Useful mini-programs

Python program: Password generator

Generate strong random passwords.

The code

import secrets
import string

def make_password(length=16):
    alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
    while True:
        pw = "".join(secrets.choice(alphabet) for _ in range(length))
        if (any(c.islower() for c in pw) and any(c.isupper() for c in pw)
                and any(c.isdigit() for c in pw)):
            return pw

pw = make_password()
print(len(pw), "characters, has a digit:", any(c.isdigit() for c in pw))

Output

16 characters, has a digit: True

How it works

Use the secrets module for anything security-related: random is predictable. The loop retries until the password has lower case, upper case and a digit. (The output does not show the password itself, because it changes every run.)

Python features used

Learn the ideas behind it in the free lesson Modules & the Standard Library.