Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

checking through a generated string for uppercase,lowercase,numbers and symbols

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading