Build a Python Password Generator in 30 Minutes — A Beginner Project With Real World Value

Build a Python Password Generator in 30 Minutes — A Beginner Project With Real World Value

The fastest way to actually learn Python is not watching tutorials.

It is building things.

Small things first. Real things. Things you can actually use — not just exercises from a textbook that solve problems nobody has outside a classroom.

In this guide you are going to build a password generator from scratch. By the end you will have a working Python program that generates strong random passwords — and you will understand every single line of it.

This project covers functions, modules, string manipulation, user input, loops, conditionals and command line interaction — all the core Python skills beginners need, applied to something genuinely useful.

✦

What You Will Build

A command line password generator that:

→ Generates cryptographically random passwords
→ Lets you choose the length
→ Lets you choose which character types to include
→ Checks how strong the password is
→ Lets you generate multiple passwords at once
→ Copies the password to your clipboard automatically

💡 What You Need

→ Python 3.6 or higher installed

→ Any code editor (VS Code recommended)

→ Basic Python knowledge (variables, loops, functions)

✦

Step 01 — Set Up Your File and Imports

Create a new file called password_generator.py and add these imports at the top:

import secrets
import string
import pyperclip

Here is what each module does:

secrets

Python's built-in module for cryptographically secure random number generation. This is important — the regular random module is not secure enough for passwords. secrets uses your operating system's random number generator which is specifically designed for security purposes.

string

Python's built-in module containing string constants. string.ascii_letters gives you all letters. string.digits gives you 0-9. string.punctuation gives you special characters. No need to type these out manually.

pyperclip

A third-party library for clipboard access. Install it with: pip install pyperclip

✦

Step 02 — Build the Core Password Generator

Add this function below your imports:

def generate_password(length=16, use_upper=True, use_lower=True,
                      use_digits=True, use_symbols=True):
    """
    Generate a secure random password.

    Args:
        length: How long the password should be
        use_upper: Include uppercase letters (A-Z)
        use_lower: Include lowercase letters (a-z)
        use_digits: Include numbers (0-9)
        use_symbols: Include special characters (!@#$ etc)

    Returns:
        A randomly generated password string
    """

    # Build the character pool based on user choices
    characters = ""

    if use_upper:
        characters += string.ascii_uppercase
    if use_lower:
        characters += string.ascii_lowercase
    if use_digits:
        characters += string.digits
    if use_symbols:
        characters += string.punctuation

    # Make sure at least one character type was selected
    if not characters:
        raise ValueError("At least one character type must be selected")

    # Generate password using secrets.choice for security
    password = "".join(secrets.choice(characters) for _ in range(length))

    return password

💡 Breaking Down the Key Line

password = "".join(secrets.choice(characters) for _ in range(length))

This single line uses a generator expression inside join(). For each number in range(length) it picks one random character from the pool using secrets.choice(). The empty string "" joins them all together without spaces. Elegant and efficient.

✦

Step 03 — Build the Password Strength Checker

Add this function below the generator:

def check_strength(password):
    """
    Check how strong a password is.
    Returns a score from 0-5 and a label.
    """
    score = 0
    feedback = []

    # Check length
    if len(password) >= 8:
        score += 1
    if len(password) >= 12:
        score += 1
    if len(password) >= 16:
        score += 1

    # Check character variety
    has_upper = any(c.isupper() for c in password)
    has_lower = any(c.islower() for c in password)
    has_digit = any(c.isdigit() for c in password)
    has_symbol = any(c in string.punctuation for c in password)

    variety_count = sum([has_upper, has_lower, has_digit, has_symbol])

    if variety_count >= 3:
        score += 1
    if variety_count == 4:
        score += 1

    # Generate feedback
    if not has_upper:
        feedback.append("Add uppercase letters")
    if not has_lower:
        feedback.append("Add lowercase letters")
    if not has_digit:
        feedback.append("Add numbers")
    if not has_symbol:
        feedback.append("Add symbols")
    if len(password) < 12:
        feedback.append("Make it longer (12+ characters)")

    # Assign label based on score
    if score <= 1:
        label = "Very Weak"
    elif score == 2:
        label = "Weak"
    elif score == 3:
        label = "Moderate"
    elif score == 4:
        label = "Strong"
    else:
        label = "Very Strong"

    return score, label, feedback

Notice the use of any() here — a powerful built-in that returns True if any item in an iterable matches the condition. This is much cleaner than writing a loop to check each character manually.

✦

Step 04 — Build the Display Function

Add this function to display results cleanly:

def display_password(password, copy_to_clipboard=True):
    """Display the password with its strength analysis."""

    score, label, feedback = check_strength(password)

    print("\n" + "="*50)
    print(f"  Generated Password:")
    print(f"  {password}")
    print("="*50)
    print(f"  Strength: {label} ({score}/5)")

    if feedback:
        print(f"  Tips: {', '.join(feedback)}")

    if copy_to_clipboard:
        try:
            pyperclip.copy(password)
            print("  ✓ Copied to clipboard!")
        except Exception:
            print("  (Clipboard copy not available)")

    print("="*50 + "\n")
✦

Step 05 — Build the User Interface

Now add the function that handles user input:

def get_user_preferences():
    """Get password preferences from the user."""

    print("\n" + "="*50)
    print("   🔐 Python Password Generator")
    print("="*50)

    # Get password length
    while True:
        try:
            length = int(input("\nPassword length (8-64) [default: 16]: ") or 16)
            if 8 <= length <= 64:
                break
            print("Please enter a number between 8 and 64")
        except ValueError:
            print("Please enter a valid number")

    # Get character type preferences
    print("\nInclude character types? (press Enter for yes, type 'n' for no)")

    use_upper = input("Uppercase letters (A-Z)? [Y/n]: ").lower() != 'n'
    use_lower = input("Lowercase letters (a-z)? [Y/n]: ").lower() != 'n'
    use_digits = input("Numbers (0-9)? [Y/n]: ").lower() != 'n'
    use_symbols = input("Symbols (!@#$)? [Y/n]: ").lower() != 'n'

    # Make sure at least one type selected
    if not any([use_upper, use_lower, use_digits, use_symbols]):
        print("\nYou must select at least one character type!")
        print("Defaulting to all character types.")
        use_upper = use_lower = use_digits = use_symbols = True

    # Get number of passwords
    while True:
        try:
            count = int(input("\nHow many passwords to generate? [default: 1]: ") or 1)
            if 1 <= count <= 10:
                break
            print("Please enter a number between 1 and 10")
        except ValueError:
            print("Please enter a valid number")

    return length, use_upper, use_lower, use_digits, use_symbols, count

💡 The While True Pattern

The while True loop with a break inside is a standard Python pattern for input validation — keep asking until you get a valid answer. The try/except ValueError catches cases where the user types text instead of a number.

✦

Step 06 — Build the Main Function

Add the main function that ties everything together:

def main():
    """Main program loop."""

    while True:
        # Get user preferences
        length, use_upper, use_lower, use_digits, use_symbols, count = get_user_preferences()

        # Generate and display passwords
        print(f"\nGenerating {count} password(s)...\n")

        for i in range(count):
            if count > 1:
                print(f"Password {i + 1}:")

            try:
                password = generate_password(
                    length=length,
                    use_upper=use_upper,
                    use_lower=use_lower,
                    use_digits=use_digits,
                    use_symbols=use_symbols
                )
                # Only copy last password to clipboard if multiple
                copy = (i == count - 1)
                display_password(password, copy_to_clipboard=copy)

            except ValueError as e:
                print(f"Error: {e}")

        # Ask if user wants to generate more
        again = input("Generate more passwords? (press Enter for yes, type 'n' to exit): ")
        if again.lower() == 'n':
            print("\nStay safe out there! 🔐\n")
            break


# Run the program
if __name__ == "__main__":
    main()

💡 The if __name__ == "__main__" Guard

This is a Python best practice. It means the main() function only runs when the file is executed directly — not when it is imported as a module into another file. Always use this pattern in Python scripts.

✦

The Complete Code

Here is the entire program in one block — ready to copy and run:

import secrets
import string
import pyperclip


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


def check_strength(password):
    score = 0
    feedback = []
    if len(password) >= 8: score += 1
    if len(password) >= 12: score += 1
    if len(password) >= 16: score += 1
    has_upper = any(c.isupper() for c in password)
    has_lower = any(c.islower() for c in password)
    has_digit = any(c.isdigit() for c in password)
    has_symbol = any(c in string.punctuation for c in password)
    variety = sum([has_upper, has_lower, has_digit, has_symbol])
    if variety >= 3: score += 1
    if variety == 4: score += 1
    if not has_upper: feedback.append("Add uppercase letters")
    if not has_lower: feedback.append("Add lowercase letters")
    if not has_digit: feedback.append("Add numbers")
    if not has_symbol: feedback.append("Add symbols")
    if len(password) < 12: feedback.append("Make it longer")
    labels = ["Very Weak", "Weak", "Moderate", "Strong", "Very Strong", "Very Strong"]
    return score, labels[score], feedback


def display_password(password, copy_to_clipboard=True):
    score, label, feedback = check_strength(password)
    print("\n" + "="*50)
    print(f"  Generated Password:")
    print(f"  {password}")
    print("="*50)
    print(f"  Strength: {label} ({score}/5)")
    if feedback:
        print(f"  Tips: {', '.join(feedback)}")
    if copy_to_clipboard:
        try:
            pyperclip.copy(password)
            print("  Copied to clipboard!")
        except Exception:
            print("  (Clipboard not available)")
    print("="*50 + "\n")


def get_user_preferences():
    print("\n" + "="*50)
    print("   Python Password Generator")
    print("="*50)
    while True:
        try:
            length = int(input("\nPassword length (8-64) [default: 16]: ") or 16)
            if 8 <= length <= 64: break
            print("Enter a number between 8 and 64")
        except ValueError:
            print("Enter a valid number")
    print("\nInclude? (Enter=yes, n=no)")
    use_upper = input("Uppercase (A-Z)? [Y/n]: ").lower() != 'n'
    use_lower = input("Lowercase (a-z)? [Y/n]: ").lower() != 'n'
    use_digits = input("Numbers (0-9)? [Y/n]: ").lower() != 'n'
    use_symbols = input("Symbols (!@#$)? [Y/n]: ").lower() != 'n'
    if not any([use_upper, use_lower, use_digits, use_symbols]):
        print("Defaulting to all types.")
        use_upper = use_lower = use_digits = use_symbols = True
    while True:
        try:
            count = int(input("\nHow many passwords? [default: 1]: ") or 1)
            if 1 <= count <= 10: break
            print("Enter a number between 1 and 10")
        except ValueError:
            print("Enter a valid number")
    return length, use_upper, use_lower, use_digits, use_symbols, count


def main():
    while True:
        length, use_upper, use_lower, use_digits, use_symbols, count = get_user_preferences()
        print(f"\nGenerating {count} password(s)...\n")
        for i in range(count):
            if count > 1:
                print(f"Password {i + 1}:")
            try:
                password = generate_password(length, use_upper,
                                             use_lower, use_digits, use_symbols)
                display_password(password, copy_to_clipboard=(i == count - 1))
            except ValueError as e:
                print(f"Error: {e}")
        if input("Generate more? [Y/n]: ").lower() == 'n':
            print("\nStay safe! 🔐\n")
            break


if __name__ == "__main__":
    main()
✦

How to Run It

01

Install pyperclip

pip install pyperclip
02

Save the complete code as password_generator.py

03

Run it from terminal

python password_generator.py
✦

Python Concepts You Just Practised

📦

Modules

secrets, string, pyperclip

🔧

Functions

Parameters, defaults, docstrings

🔄

Loops

while True, for loops, break

⚠️

Error Handling

try/except, raise ValueError

⚡

Comprehensions

Generator expressions, any()

✦

Challenge Yourself — Ways to Extend This Project

🚀 Beginner Challenges

→ Add an option to exclude similar-looking characters (0, O, l, 1, I)

→ Save generated passwords to a text file with timestamps

→ Add a custom symbol set option

⚡ Intermediate Challenges

→ Build a GUI version using tkinter

→ Add a passphrase generator (random words from a word list)

→ Check if generated password has been in known data breaches using the HaveIBeenPwned API

🔥 Advanced Challenges

→ Build an encrypted local password manager that stores and retrieves passwords

→ Create a web version using Flask

→ Add command line arguments using argparse so it works without interactive prompts

🎯 Key Takeaway

Every real Python skill you will ever need — modules, functions, error handling, loops, user input, string manipulation — appears in this one small project. This is how learning programming actually works. Not by studying concepts in isolation but by building things that require you to connect them. The project gives the concepts a reason to exist. And a reason to stick.

Final Words

You just built something real.

Not a hello world. Not a textbook exercise. A working program that solves an actual problem — one you can run on your computer, share with friends and extend in any direction you choose.

That is what programming actually feels like. Build the next thing. Then the next. Each project teaches you more than any tutorial — because each project forces you to connect what you know in a new way. That connection is where real understanding lives.

🚀 Build It Right Now

Step 1 → pip install pyperclip

Step 2 → Copy the complete code into password_generator.py

Step 3 → Run it and generate your first secure password

Keep learning. Keep building. 🚀

Follow StudyWithBro on Pinterest for Python projects, coding guides and programming tutorials.

Comments

Popular posts from this blog

Best Laptops for Programming Students in India 2026

How to Use GitHub Complete Beginner Guide (2026)

Best Study System for Students in 2026 (Study Smarter Not Harder)