Recommended Python password generator
This reusable function generates a 20-character password and requires uppercase, lowercase, numeric, and punctuation characters.
import secrets
import string
def generate_password(length=20):
if length < 4:
raise ValueError("length must be at least 4")
alphabet = string.ascii_letters + string.digits + string.punctuation
while True:
password = "".join(secrets.choice(alphabet) for _ in range(length))
if (
any(char.islower() for char in password)
and any(char.isupper() for char in password)
and any(char.isdigit() for char in password)
and any(char in string.punctuation for char in password)
):
return password
print(generate_password())
Run it with python3 password_generator.py. Each character is selected independently from the complete alphabet until the result satisfies the stated policy.
Use secrets, not random
Python documents secrets as the module for passwords, authentication tokens, and related secrets. The default random module uses a deterministic generator intended for simulation and is unsuitable for cryptographic use.
secrets.choice(alphabet) asks the operating system's secure random source to select from the supplied sequence. Do not substitute random.choice, seed a predictable generator, or build passwords from timestamps.
How the function works
string.ascii_letters,string.digits, andstring.punctuationdefine the allowed characters.- The generator selects
lengthindependent characters withsecrets.choice. - The four checks confirm the result contains every required character group.
- If a group is missing, the whole candidate is discarded and a fresh candidate is generated.
This rejection approach follows the pattern in Python's official password recipe. It keeps each accepted result within the stated policy without inserting predictable characters at fixed positions.
Generate an alphanumeric password
Use an alphanumeric alphabet when the destination does not accept punctuation. Increase the length when possible because the available alphabet is smaller.
import secrets
import string
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(24))
print(password)
If the destination also requires at least one uppercase letter, lowercase letter, and digit, apply the same validation loop used in the full function.
Generate multiple passwords in Python
Call the function repeatedly for test fixtures, administrator-created temporary credentials, or other authorized workflows. A set prevents an accidental duplicate inside the batch.
passwords = set()
while len(passwords) < 10:
passwords.add(generate_password(24))
for password in passwords:
print(password)
One-line command
For an occasional local password, run this command in a trusted terminal:
python3 -c 'import secrets,string; a=string.ascii_letters+string.digits+string.punctuation; print("".join(secrets.choice(a) for _ in range(20)))'
The compact command does not guarantee every character group. Use the reusable function when a form requires specific groups.
Password versus token generation
A password is normally entered by a person or stored in a password manager. An application token is usually machine-generated and machine-consumed. Python provides purpose-built token helpers:
secrets.token_urlsafe(32)creates a URL-safe token from 32 random bytes.secrets.token_hex(32)creates 64 hexadecimal characters from 32 random bytes.secrets.token_bytes(32)returns raw bytes for code that needs binary key material.
Use the site's random token generator when you want equivalent Base64URL or hexadecimal output in the browser.
Common mistakes
- Using
random: reproducibility is useful for simulations and tests, but it is the wrong property for credentials. - Generating too few characters: a four-group requirement does not make a short password strong. Use a longer value whenever the destination allows it.
- Forcing fixed positions: patterns such as “uppercase first, digit last” make the format more predictable.
- Removing rejected characters afterward: deletion changes the length and can create uneven output. Define the allowed alphabet before selection.
- Logging the result: secure generation cannot protect a password exposed by application logs or error reports.
- Storing plaintext passwords: applications that verify user passwords should use an appropriate salted password-hashing system, not reversible storage.
Test the generator
Automated tests should verify length, allowed characters, and required groups across many generated samples. Do not test for one exact output because secure results are intentionally not reproducible.
for _ in range(1_000):
value = generate_password(20)
assert len(value) == 20
assert any(char.islower() for char in value)
assert any(char.isupper() for char in value)
assert any(char.isdigit() for char in value)
assert any(char in string.punctuation for char in value)
No code required
If you need a password rather than a Python project, use the browser password generator. It uses the Web Crypto API, runs locally, and provides length and compatibility controls. For a JVM implementation, use the Java password generator guide. For a deeper implementation discussion, read the password-generating algorithm guide.
Sources and tested scope
The examples use only Python's standard library. They were executed with Python 3 and reviewed against the current Python 3.14 documentation on October 2, 2026.