currently attempting to scan through an automatically generated string based on the length of a password , if the password does not contain an uppercase,lowercase, symbol and number a condtion should be triggered in the if statement in which will iterate until a string with the condtions is generated. however the iteration never stops despite whether an string meets its condtion or not.
im sure the error is in the while loop but i cannot figure out the problem with the while loop
code:
import random
passlen = int(input("Enter the length of password: \n"))
s="abcdefghijklmnopqrstuvwxyz"
ss="01234567890"
sss="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ssss="!@#$%^&*()"
comb = s+ss+sss+ssss
p = "".join(random.sample(comb,passlen ))
while(s not in p and ss not in p and sss not in p and ssss not in p):
p = "".join(random.sample(comb,passlen ))
print ("The generated password: ", p)
>Solution :
Your code looks for the substrings "ABCD…XYZ", "abcd…xyz", "012…789", and the string listing out all the possible special characters. Unless you’re trying to generate a password of length at least 26 + 26 + 10 + 10 = 72, those substrings can never appear in your password, so your code loops infinitely.
Rejection sampling isn’t necessary here. You can pick one character from each of your four categories, select the remaining characters from the combination of all four categories, and then shuffle the characters.
import random
passlen = int(input("Enter the length of password: \n"))
lowercase_letters="abcdefghijklmnopqrstuvwxyz"
numbers="01234567890"
uppercase_letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
special_characters="!@#$%^&*()"
combined_characters = lowercase_letters + uppercase_letters + numbers + special_characters
password_characters = []
for category in [lowercase_letters, numbers, uppercase_letters, special_characters]:
password_characters.append(random.choice(category))
password_characters.extend(random.sample(combined_characters, passlen - 4))
random.shuffle(password_characters)
print("The generated password:", "".join(password_characters))