I have a dictionary called "user_database" that holds users, and a variable called "registered_users" that increments as the input is called in a "while True" loop. How can I endlessly add new users to the dictionary as the inputs are entered?
this is what I have, (BTW I am a beginner at python)
user_database = {
"username": "my_username",
"password": "my_password"
}
registered_users = 1
def register_user(user_database):
if user_database:
while True:
for i in range(3):
registered_users = i += 1
username = input("Enter your username: ")
password = input("Enter your password: ")
user_database[f'username_{registered_users}'] = username
user_database[f'password_{registered_users}'] = password
print(user_database)
continue
register_user(user_database)
here is the output:
Enter your username: sunshine
Enter your password: sunshine123
{'username': 'my_username', 'password': 'my_password', 'username_1': 'sunshine', 'password_1': 'sunshine123'}
Enter your username: sunshine_2
Enter your password: sunshine555
{'username': 'my_username', 'password': 'my_password', 'username_1': 'sunshine_2', 'password_1': 'sunshine555'}
Enter your username:
It is not adding A NEW key:value pair on EACH entry, its simply replacing the extra one.
I want to add a new key:pair upon each username & password input entry.
I have tried update() and It did the same thing. Although I may have used it incorrectly.
>Solution :
Something like this would do what you would want:
user_database = [{
"username": "my_username",
"password": "my_password"
}]
registered_users = 1
def register_user(user_database):
global registered_users
if user_database:
while True:
registered_users += 1
new_user = {}
username = input("Enter your username: ")
password = input("Enter your password: ")
new_user[f'username_{registered_users}'] = username
new_user[f'password_{registered_users}'] = password
user_base.append(new_user)
register_user(user_database)
In the following, the registered users are saved in a list. In this list, there are dictionaries for each user containing a key for the username and a key for the password, which is entered in the while loop. You would want to find a way to break out of the while loop yourself, otherwise you will keep going on forever. This is simply done by adding a closing condition that executes a break. For good measure, I have added that the variable registered_users is uses the global variable.