Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Generate Strong Random Passwords with Custom Rules in Python

Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.

Easy Python 3.9+ Jun 27, 2026 Automation & scripting 1 views 0 copies

Python code

21 lines
Python 3.9+
import secrets
import string

def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
    pool = ''
    if use_lower:
        pool += string.ascii_lowercase
    if use_upper:
        pool += string.ascii_uppercase
    if use_digits:
        pool += string.digits
    if use_punct:
        pool += string.punctuation
    if not pool:
        raise ValueError("At least one character set must be enabled.")
    return ''.join(secrets.choice(pool) for _ in range(length))

if __name__ == "__main__":
    print(generate_password())
    print(generate_password(12, use_punct=False))
    print(generate_password(20, use_lower=False, use_digits=False))

Output

stdout
M7@jK#l9XzQ2$rTp
bC3@kL9dF2
Q#W$E%R&T*Y^U(I)O_P

How it works

The secrets module is preferred over random for generating cryptographically secure passwords. The function builds a character pool from string constants based on the user's boolean flags, then selects characters using secrets.choice(). The check if not pool ensures at least one character set is enabled, preventing an infinite loop or empty password. By default, the function generates a 16-character password with all character types, but you can adjust length and disable any set by passing False.

Common mistakes

  • Using `random` instead of `secrets`, which is not suitable for passwords because it is not cryptographically secure.
  • Forgetting to check that at least one character set is enabled, leading to an empty password or error.
  • Using `string.whitespace` or other characters that might cause issues in URLs or command-line environments.

Variations

  1. Use `os.urandom` with base64 encoding for a simpler password format without choosing character sets.
  2. Add a `unique_chars` parameter that ensures no duplicate characters in the password by sampling without replacement.

Real-world use cases

  • Generating temporary admin passwords when provisioning cloud VMs or databases via automation scripts.
  • Creating user-friendly passwords for internal tool accounts where certain special characters must be avoided.
  • Automatically rotating API keys or service account secrets that require a specific mix of character types.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.