PythonMastery

Password generator in Python

Generate random passwords that always contain a lowercase letter, a capital, a digit and a symbol. Also shows the secrets module for real passwords.

A password generator picks characters at random from a set of allowed characters. This version also makes sure every password has at least one lowercase letter, one capital letter, one digit and one symbol.

The program

python
import random
import string

# fixed seed so the output matches this page; remove it for real use
random.seed(7)


def make_password(length=12):
    if length < 4:
        raise ValueError("length must be at least 4")
    groups = [string.ascii_lowercase, string.ascii_uppercase, string.digits, string.punctuation]
    # one character from each group, so every password contains all four kinds
    chars = [random.choice(group) for group in groups]
    all_chars = "".join(groups)
    chars += random.choices(all_chars, k=length - len(groups))
    random.shuffle(chars)
    return "".join(chars)


for length in [8, 12, 16]:
    print(length, make_password(length))
output
8 E6YgfIk$
12 6l$2|LRu:6`c
16 9Cf-QdD3OZ-tJ"Sf

How it works

For real passwords: use secrets

The random module is made for games and simulations. Its numbers can be predicted if someone knows enough of its earlier output. For passwords, tokens and keys, use the secrets module, which uses the operating system's secure random source:

python
import secrets
import string

alphabet = string.ascii_letters + string.digits + string.punctuation
password = "".join(secrets.choice(alphabet) for _ in range(16))
print(password)

This block has no output shown because it prints a different password every time it runs. secrets has no seed, and that is the point: nobody can repeat its results.

Learn the idea: Working with Strings, pip & the Standard Library: Batteries Included

A longer explanation: Project: Password Generator