Password Generator in Python

Generating strong and unique passwords is essential for maintaining security in today’s digital landscape. To make this process more accessible and user-friendly, we can create a Python script that not only generates passwords based on user preferences but also provides a clear and interactive interface. In this example, we’ll build a command-line tool that asks the user for input on password length and the inclusion of various character types, then generates a secure password accordingly.

Code Example

import random
import string

def generate_password(length, use_uppercase, use_digits, use_punctuation):
    characters = string.ascii_lowercase
    if use_uppercase:
        characters += string.ascii_uppercase
    if use_digits:
        characters += string.digits
    if use_punctuation:
        characters += string.punctuation

    if not characters:
        raise ValueError("At least one character set must be selected")

    password = ''.join(random.choice(characters) for i in range(length))
    return password

def main():
    print("Welcome to the Password Generator!")
    while True:
        try:
            length = int(input("Enter the desired password length (e.g., 12): "))
            if length <= 0:
                print("Length must be a positive number.")
                continue
        except ValueError:
            print("Invalid input. Please enter a number.")
            continue

        use_uppercase = input("Include uppercase letters? (yes/no): ").strip().lower() == 'yes'
        use_digits = input("Include digits? (yes/no): ").strip().lower() == 'yes'
        use_punctuation = input("Include special characters? (yes/no): ").strip().lower() == 'yes'

        try:
            password = generate_password(length, use_uppercase, use_digits, use_punctuation)
            print(f"Generated password: {password}")
        except ValueError as e:
            print(e)

        another = input("Generate another password? (yes/no): ").strip().lower()
        if another != 'yes':
            print("Thank you for using the Password Generator. Goodbye!")
            break

if __name__ == "__main__":
    main()

Detailed Code Explanation

Importing Required Modules

import random
import string
  • random: This module provides functions for generating random numbers and selecting random items.
  • string: This module provides constants for common string operations, including predefined sets of characters (e.g., lowercase, uppercase, digits, punctuation).

Password Generation Function

def generate_password(length, use_uppercase, use_digits, use_punctuation):
    characters = string.ascii_lowercase
    if use_uppercase:
        characters += string.ascii_uppercase
    if use_digits:
        characters += string.digits
    if use_punctuation:
        characters += string.punctuation

    if not characters:
        raise ValueError("At least one character set must be selected")

    password = ''.join(random.choice(characters) for i in range(length))
    return password
  1. Function Definition: generate_password(length, use_uppercase, use_digits, use_punctuation)
    • length: Desired length of the password.
    • use_uppercase: Boolean indicating whether to include uppercase letters.
    • use_digits: Boolean indicating whether to include digits.
    • use_punctuation: Boolean indicating whether to include special characters.
  2. Initial Character Set: characters = string.ascii_lowercase
    • Starts with lowercase letters.
  3. Conditionally Add Character Sets:
    • if use_uppercase: characters += string.ascii_uppercase
    • if use_digits: characters += string.digits
    • if use_punctuation: characters += string.punctuation
  4. Validation: Check if characters is empty, meaning no character sets were selected. If so, raise a ValueError.
  5. Password Generation: Use a list comprehension inside ''.join() to generate a random password of the specified length from the selected characters.
  6. Return Password: The generated password is returned.

Main Function

def main():
    print("Welcome to the Password Generator!")
    while True:
        try:
            length = int(input("Enter the desired password length (e.g., 12): "))
            if length <= 0:
                print("Length must be a positive number.")
                continue
        except ValueError:
            print("Invalid input. Please enter a number.")
            continue

        use_uppercase = input("Include uppercase letters? (yes/no): ").strip().lower() == 'yes'
        use_digits = input("Include digits? (yes/no): ").strip().lower() == 'yes'
        use_punctuation = input("Include special characters? (yes/no): ").strip().lower() == 'yes'

        try:
            password = generate_password(length, use_uppercase, use_digits, use_punctuation)
            print(f"Generated password: {password}")
        except ValueError as e:
            print(e)

        another = input("Generate another password? (yes/no): ").strip().lower()
        if another != 'yes':
            print("Thank you for using the Password Generator. Goodbye!")
            break
  1. Greeting: Print a welcome message.
  2. Infinite Loop: while True: allows the user to generate multiple passwords without restarting the program.
  3. Password Length Input:
    • length = int(input("Enter the desired password length (e.g., 12): "))
    • If the input is not a valid integer or is less than or equal to 0, an error message is displayed, and the loop continues.
  4. Character Set Preferences:
    • Prompt the user to include uppercase letters, digits, and special characters.
    • Convert input to lowercase and compare with ‘yes’ to get boolean values.
  5. Generate Password:
    • Call generate_password() with the specified parameters.
    • Handle any ValueError raised (e.g., if no character sets are selected).
  6. Display Password: Print the generated password.
  7. Another Password?:
    • Ask the user if they want to generate another password.
    • If the input is not ‘yes’, exit the loop and print a goodbye message.

Entry Point

if __name__ == "__main__":
    main()
  • Entry Point Check: This ensures the main() function is called only when the script is run directly, not when imported as a module.