Click here to Skip to main content
16,016,781 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello this is Gulshan Negi
Well, I am writing a program for password generation in Python but it shows some error while executing.
Source Code:

Python
import secrets
import string

def create_pw(pw_length=12):
   letters = string.ascii_letters
   digits = string.digits
   special_chars = string.punctuation

   alphabet = letters + digits + special_chars
   pwd = ''
   pw_strong = False

   while not pw_strong:
       pwd = ''
       for i in range(pw_length):
           pwd = ''.join(secrets.choice(alphabet))

       if (any(char in special_chars for char in pwd) and
               sum(char in digits for char in pwd) >= 2):
           pw_strong = True

   return pwd

if __name__ == '__main__':
   print(create_pw())


I had also taken its reference from 30 Cool, Easy & Fun Python Projects with Source Code [2023][^] but I don't know what I am missing here. Can anyone give their suggestions on this.
Thanks

What I have tried:

I take reference from many resources but not able to execute the program.
Posted
Updated 7-Apr-23 7:35am
v2

Try this:
for i in range(pw_length):
    pwd = pwd + secrets.choice(alphabet)
But ... that's a very inefficient way to generate it - there is no guarantee that the random sequences generated will ever meet the criteria which allows it to return a password, particularly as the length drops.

There are two ways to fix that: generate three indexes - one for a special character, two for digits. As you loop through the "create a password loop, check the current index: if it matches the special character index, add one of those. If it matches one of the digit indexes, add one of those. Otherwise, add a letter.

That way, the resulting string will always meet the criteria, and the generation time will be consistent.
 
Share this answer
 
You are getting an infinitie loop because of the following lines:
Python
for i in range(pw_length):
    pwd = ''.join(secrets.choice(alphabet)) # you replace pwd with a single character each time

So the code at ...
Python
if (any(char in special_chars for char in pwd) and
        sum(char in digits for char in pwd) >= 2):
    pw_strong = True

... will never set pw_strong = True
So change it to:
Python
while not pw_strong:
   for i in range(pw_length):
       pwd += ''.join(secrets.choice(alphabet)) # append each character to the pwd variable, until it has pw_length characters

[edit]
See secrets — Generate secure random numbers for managing secrets — Python 3.11.2 documentation[^] for suggested usage of the secrets module.
[/edit]
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900