Rayzenert
Rayzenert

Reputation: 9

Why is my password generator only generating one password?

Im a beginner to python and wish for help with this

print('Password generator ')
letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*().,?0123456789'
numv = int(input('Amounts of Passwords to generate:'))
leny = input('Input your password length:')
leny = int(leny)
print('Here are your passwords:')
for pwd in range(numv):
    passwords = ''
for c in range(leny):
    passwords += random.choice(letter)
print(passwords)

I don't understand why it isn't printing out more than one password when I run it.

Upvotes: 0

Views: 146

Answers (1)

Rayan Hatout
Rayan Hatout

Reputation: 640

What you want to do is nest the second for-loop in the first one.

for pwd in range(numv):
    passwords = ''

This for-loop doesn't do anything as of right now it is equivalent as if you had just written:

passwords = ''

To achieve the desired behaviour you'd need to do something like this:

passwords = ''
for pwd in range(numv):
    for c in range(leny):
        passwords += random.choice(letter)
    passwords += "|" # This is just a separator 

You'll notice I added passwords += "|" at the end of every iteration of the outer for-loop. This is just for you to be able to distinguish the different passwords when you print the string later. Without it the output would look like password1password2password3 but with it you'd get password1|password2|password3

An even better approach is to declare passwords as a list and append the different passwords to that list:

passwords = []
for pwd in range(numv):
    password = ""
    for c in range(leny):
        password += random.choice(letter)
    passwords.append(password)

for password in passwords:
    print(password)

Upvotes: 1

Related Questions