Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Projects
  3. Build a Password Generator in Python

Project 6 · Guided build

Build a Password Generator in Python

Generate passwords from configurable character sets, enforce minimum length, and evaluate basic strength.

Open the compilerWarm-up exercises
beginner45–60 minutesstringsrandom and secretsloopsvalidation
On this page
  1. What you will build
  2. Character sets
  3. A first generator
  4. Guaranteeing character variety
  5. Using secrets
  6. Validation
  7. Strength report
  8. Testing checklist
  9. Stretch goals

A password generator is a small program with clear requirements and several useful edge cases. You will build one that lets the user choose a length and character sets, then produce a password and a short strength report.

What you will build#

A console tool that:

  • Asks for a password length.
  • Asks whether to include digits and symbols.
  • Validates the choices.
  • Generates a password containing at least one character from each selected set.
  • Prints the password and its length.
  • Refuses lengths below 8 and above 128.

Character sets#

Python
import string

lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase
digits = string.digits
symbols = "!@#$%^&*()-_=+[]{};:,.?/"

Keep the sets explicit. Do not include ambiguous lookalike characters such as O, 0, l, and 1 in a password meant for manual entry unless the user asks for them.

A first generator#

Python
import random

alphabet = lowercase + uppercase + digits
length = 12
password = "".join(random.choice(alphabet) for _ in range(length))
print(password)

random.choice() picks one character. The generator expression runs once per position.

Guaranteeing character variety#

Choosing independently from the full alphabet can produce a password with no digits, even when digits are enabled. Guarantee one from each required set, then fill the remainder:

Python
def generate_password(length, required_sets):
    if length < len(required_sets):
        raise ValueError("Length is too short for the selected character sets")

    characters = [random.choice(characters_set) for characters_set in required_sets]
    alphabet = "".join(required_sets)

    while len(characters) < length:
        characters.append(random.choice(alphabet))

    random.shuffle(characters)
    return "".join(characters)

Shuffling matters: without it, the first characters always come from known sets, which leaks structure.

Using secrets#

random is not designed for security-sensitive tokens. Use the secrets module when the password protects a real account:

Python
import secrets

def secure_password(length, required_sets):
    characters = [secrets.choice(characters_set) for characters_set in required_sets]
    alphabet = "".join(required_sets)

    while len(characters) < length:
        characters.append(secrets.choice(alphabet))

    secrets.SystemRandom().shuffle(characters)
    return "".join(characters)

secrets.choice() uses the operating system's secure random source. secrets.SystemRandom().shuffle() shuffles securely. The generator still needs the same validation.

Validation#

Python
def read_length():
    text = input("Password length (8-128): ").strip()
    try:
        length = int(text)
    except ValueError:
        print("Enter a whole number.")
        return None

    if not 8 <= length <= 128:
        print("Length must be between 8 and 128.")
        return None

    return length

Ask for yes/no options explicitly and default to safe values:

Python
use_digits = input("Include digits? (y/N): ").strip().lower() == "y"
use_symbols = input("Include symbols? (y/N): ").strip().lower() == "y"

Only y enables an option, so pressing Enter keeps it off. This is a safer default than treating any answer as yes.

Strength report#

Avoid claiming a password is "unbreakable" or assigning an exact crack time. State what the generator knows:

Python
pool_size = len(alphabet)
entropy_bits = length * (pool_size.bit_length())
print(f"Length: {length}")
print(f"Character pool: {pool_size}")
print(f"Approximate entropy: {entropy_bits} bits")

This rough estimate assumes every character is chosen independently from a uniform alphabet. The guarantee step changes the distribution slightly, so label the number approximate. For a precise audit, use a dedicated password-strength library in a full Python environment.

Do not log generated passwords

Avoid printing passwords to shared logs, storing them in source files, or sending them over chat. Generate them locally and place them directly in a password manager.

Testing checklist#

  • Generate a 12-character password with digits and symbols.
  • Verify the length is exactly 12.
  • Confirm at least one digit and one symbol when selected.
  • Try length 7, 129, abc, and a blank line.
  • Generate several passwords and confirm they differ.
  • Check the all-letters configuration.

Stretch goals#

  • Add a passphrase mode that joins random words from a list.
  • Exclude ambiguous characters with an option.
  • Copy the password to the clipboard with pyperclip in a local environment.
  • Write a function that measures unique characters and repeated runs.
  • Compare random and secrets output distributions with a large sample.
Previous projectBuild an Expense Tracker in PythonNext projectBuild a Text Adventure in Python

On this page

  1. What you will build
  2. Character sets
  3. A first generator
  4. Guaranteeing character variety
  5. Using secrets
  6. Validation
  7. Strength report
  8. Testing checklist
  9. Stretch goals

Project checklist

  • Read the requirements.
  • Plan the data model.
  • Build one feature at a time.
  • Test invalid input.
  • Refactor after it works.