Password Generator Python Code


Password Generator Python Code


import random
import string

def generate_password(length=12, use_letters=True, use_numbers=True):
    characters = ''
    if use_letters:
        characters += string.ascii_letters
    if use_numbers:
        characters += string.digits

    if not characters:
        raise ValueError("At least one character type (letters or numbers) must be selected.")

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

# Usage example
use_letters = input("Include letters in the password? (yes/no): ").lower() == 'yes'
use_numbers = input("Include numbers in the password? (yes/no): ").lower() == 'yes'
password_length = int(input("Enter the length of the password: "))

generated_password = generate_password(length=password_length, use_letters=use_letters, use_numbers=use_numbers)
print("Generated password:", generated_password)
 

Description: This Python code generates random passwords based on user-defined criteria. It includes options to include letters, numbers, or both in the generated password. The user can specify the length of the password and whether to include letters, numbers, or both. The generated password is displayed as output.

Usage:

  1. Run the code snippet in a Python environment.
  2. Follow the prompts to specify the length of the password and whether to include letters and/or numbers.
  3. The generated password will be displayed as output.

 
 
Previous Post Next Post

Contact Form