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
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)