password generator in python
import random
import string
def generate_password(length=12, use_uppercase=True, use_digits=True, use_specials=True):
# Define character sets
lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase if use_uppercase else ''
digits = string.digits if use_digits else ''
specials = string.punctuation if use_specials else ''
all_chars = lowercase + uppercase + digits + specials
if not all_chars:
raise ValueError("At least one character set must be enabled")
# Make sure the password includes at least one of each selected type
password = []
if use_uppercase:
password.append(random.choice(uppercase))
if use_digits:
password.append(random.choice(digits))
if use_specials:
password.append(random.choice(specials))
# Fill the rest of the password length
while len(password) < length:
password.append(random.choice(all_chars))
# Shuffle to ensure randomness
random.shuffle(password)
return ''.join(password)
# Example usage
print("Generated Password:", generate_password(length=8))
0 Comments