I have made a random password generator using a class called password
and a method called generate
.
My program works as it should. It generates a random password determined by the users preferences for length, upper or lowercase, numbers and special characters.
I was just wondering if there was a way to refactor the numerous if
statements I have used to determine what sort of password the program would generate.
Any other suggestions for improvements I could make would also be helpful. Thanks a ton :D
Code:
import random import string class password: def __init__(self, length, string_method, numbers=True, special_chars=False): self.length = length self.string_method = string_method self.numbers = numbers self.special_chars = special_chars def generate(self, iterations): # Checking what type of string method the user has asked for if self.string_method == 'upper': stringMethod = string.ascii_uppercase elif self.string_method == 'lower': stringMethod = string.ascii_lowercase elif self.string_method == 'both': stringMethod = string.ascii_letters # Checking if the user has asked for numbers or not if self.numbers == True: stringNumbers = string.digits elif self.numbers == False: stringNumbers = '' # Checking if the user has asked for special characters or not if self.special_chars == True: stringSpecial = string.punctuation elif self.special_chars == False: stringSpecial = '' characters = stringMethod + stringNumbers + stringSpecial # Generating the password for p in range(iterations): output_password = '' for c in range(self.length): output_password += random.choice(characters) print(output_password) # Test password1 = password(20, 'lower', True, False) # password length = 20, string method is lowercase, numbers are true and special characters are false password1.generate(3) # generate the random password 3 times
if
-else
instead ofif
-elif
? What happens with unexpected input?\$\endgroup\$