TransWikia.com

Password Generating program in python

Stack Overflow Asked by M Ismail on February 20, 2021

I have generated random passwords. Now i want to assign each password to each/different users present in the users list. but only the last password is being assigned to each user. The code is below.

import random

chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456!@#$%^&*()"
users=['A','B','C']


users_count= 0
for i in users: 
      users_count = users_count + 1
# print (str(users_count))



pass_len=int(input("Password length = "))
pass_count=users_count

for i in range(0,pass_count):
    password=""
    for i in range(0,pass_len):
        pass_chars= random.choice(chars)
        password=password+pass_chars 
    print("all pass are : " ,password)
 
for user in users:
    print(user," Password : ",password)

The output is like this:

Password length = 5
all pass are :  As6iI
all pass are :  FhAIX
all pass are :  fjJBH
A  Password :  fjJBH
B  Password :  fjJBH
C  Password :  fjJBH

2 Answers

Use a dictionary to store the pairs <user, password>.

user_passwords = {}
for user in users: # For each user
    password = ""
    for i in range(0, pass_len): # Lets generate the password
        password = password + random.choice(chars) # Add a random character
    user_passwords[user] = password # assign the password to the user

for user in users:
    print(user," Password : ",user_passwords[user])

or a shorter version:

user_passwords = {}
for user in users:
    for i in range(0, pass_len):
        user_passwords[user] = user_passwords.get(user, "") + random.choice(chars)

for user in users:
    print(user," Password : ",user_passwords[user])

The problem with your code:

password=""
for i in range(0,pass_len):
    pass_chars= random.choice(chars)
    password=password+pass_chars 
print("all pass are : " ,password) 
        #   <-- Missing assigning the password to the user

was that you were generating random passwords but not assigning them to the users.

but only the last password is being assigned to each user. The code is below.

That is because you were iterating over the users, by print always the last password that were generated previously:

for user in users:
    print(user," Password : ",password)

Correct answer by dreamcrash on February 20, 2021

'password' is a variable that can only have 1 value at a time, when you change the value of password in a loop, when the loop ends, only the last value will remain.

Create an array and append the passwords to it in a loop, then call the array in a loop for each user.

Answered by Adi on February 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP