How to iterate in a list of multiple dictionaries - python-3.x

I'm writing a simple code to ask for username and password, and match those information in a database. And if the username is not in the database I ask the user if he want's to sign up, and then add that information to the database.
Everything in the code works well. except when I add another user in the database.
In this code, if the user enters Bob and password test123, the user is identified in the database and the code exits. However, if they user enters Rolf, it's not identified and he's asked to signup.
How can I adjust the code to iterate over the whole database.
Code
database = [{"username": 'Bob', "Password": 'test123'},{"username": 'Rolf', "Password": "password2"}]
def askuser():
input_username = input("Please enter your username: ")
input_password = input("Please enter your password: ")
for user in database:
if user["username"] == input_username and user["Password"] == input_password:
print(f"username {input_username} is correct, welcome to the program")
break
else:
choice = input(f"username {input_username} doesnt exist, do you want to sign up Y/n : ")
choice.strip('')
if choice == "Y":
while True:
input_desireduser = input("Please enter your desired username: ")
input_desiredpass = input("Please enter your desired password: ")
input_desiredpassconf = input("Please enter your desired password again: ")
if (input_desiredpassconf != input_desiredpass):
print("Your passwords doesn't match, please enter them again !!")
continue
else:
print("Thank you, your account is created")
database.append({"username": input_desireduser, "Password": input_desiredpass})
break
else:
print("Thank you !!")
break
return database
askuser()

The problem comes from the if/else even though there multiples problems.
Let's say I type Rudolph and the correct password.
1st loop :
if Bob == Rudolph is False, hence it will execute the else part.
You'll have to loop over the list and gather a boolean using mybool = mybool or my condition.
then check afterward.
Is it mandatory to use a list of dictionaries ?
In this exemples it doesn't make sense.
Here is one without a list of dict
database = {'bob':'test123','Rudolph':'password'}
defAskUser()
input_username = input("Please enter your username: ")
input_password = input("Please enter your password: ")
try:
password = dataset[input_username]
if password == input_password:
print(f"username {input_username} is correct, welcome to the program")
except KeyError:
choice = input(f"username {input_username} doesnt exist, do you want to sign up Y/n : ")
choice.strip('')
if choice == "Y":
input_desireduser = input("Please enter your desired username: ")
input_desiredpass = input("Please enter your desired password: ")
input_desiredpassconf = input("Please enter your desired password again: ")
if (input_desiredpassconf != input_desiredpass):
print("Your passwords doesn't match, please enter them again !!")
continue
else:
print("Thank you, your account is created")
database.append({input_desireduser:input_desiredpass})
break
else:
print("Thank you !!")
break

Related

password and username validation with some condition

I have to create code that validates whether a password:
Contains at least 1 number
Contains at least 1 capital letter
Contains at least 1 lowercase letter
Contains at least 1 special symbol
and again ask the username and password (the previous one that we entered) if enter the wrong one after 3rd attempt it will print account blocked! (can someone help to fix my code please)
import re
def main():
username = 'qqq'
password = '12q#3A'
reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*#?&])[A-Za-z\d#$!#%*?&]"
# compiling regex
pat = re.compile(reg)
# searching regex
mat = re.search(pat, password)
# validating conditions
if mat:
print("Password is valid.")
userInput = input("What is your username?\n")
if userInput == username:
for i in range (3,0,-1):
userinput = input("Password?\n")
if userinput == password:
break
else:
print("That is the wrong password and try again")
if i==1:
print("Account BLOCKED")
else:
print(" You have succe")
else:
print("That is the wrong username.")
else:
print("Password invalid !!")
# Driver Code
if __name__ == '__main__':
main()
As stated in the comments, there are already mature libraries for the task. Also, never store passwords as plaintext.
This script will ask user 3 times for correct password, if user fails to enter valid password, print Account blocked!:
import re
def check(password):
""" Return True if password
Contains at least 1 number *AND*
Contains at least 1 capital letter *AND*
Contains at least 1 small letter *AND*
Contains at least 1 special symbol
False otherwise
"""
return bool(re.search(r'\d', password) and
re.search(r'[A-Z]', password) and
re.search(r'[a-z]', password) and
re.search(r'[#$!%*#?&]', password))
username = input('Please enter your username: ')
for attempt in range(1, 4):
password = input('Please enter your password: ')
if check(password):
print('Password is OK!')
break
print('Invalid password, attempts left {}'.format(3 - attempt))
else:
print('Account blocked!')
Prints (for example):
Please enter your username: Andrej
Please enter your password: we
Invalid password, attempts left 2
Please enter your password: wew
Invalid password, attempts left 1
Please enter your password: wew
Invalid password, attempts left 0
Account blocked!
Or:
Please enter your username: Andrej
Please enter your password: A1#a
Password is OK!

For loop skipping login verfication

The for loop is skipping over the if statements when the loop is complete or at least thats what I think it is doing. Let me know what I need to revise. The dictionary has usernames and passwords stored in from inputted new users.
import json
users = {}
def create_new_login():
new_username = (input("Please enter a username: "))
new_password = (input("Please enter a password: "))
filename = 'login.json'
if new_username in users.keys():
input("Please input a new username")
elif new_password in users.values():
input("Please input a new password")
else:
users.update({new_username : new_password})
with open(filename, 'a') as file_object:
json.dump(users, file_object)
def check_username():
"""Checks username and password"""
#User inputs username and password
username_input = input("Please enter your username: ")
for key in users.keys(): #Checks username and password
if username_input == key:
check_password()
else:
print("Incorrect login")
def check_password():
password_input = input("Please enter your password: ")
for value in users.values():
if password_input == value:
print("Welcome back " + users)
welcome = input("Are you a new user?(yes or no): ")
if welcome == 'yes':
create_new_login()
if welcome == 'no':
check_username()
I expect if the username entered is in the dictionary then it will run the check_password function and do the same task for the password. But upon completion it will say "Welcome back " + the username inputted. Also if someone could explain how instead of using users for the welcome back I could use the password given to find the key for that value in the dictionary.
You've written the json file but are not reading from it. Every time you re-run the program you start at the top and initialize users = {}. Put a print statement in the for loop and you will find that users.keys() is dict_keys([]) is empty. And this makes the for loop "skip over" if because it fails the condition. What you ought to do is to read from the json file and then check the condition.

Check if two inputs have same index in 2 different lists

Hi everyone i need help for my computing project but cant find an answer on google. Im trying to make a basic login system and have 2 lists, one list with usernames and one with passwords:
usernames[username1, username2, username3, etc]
passwords[password1, password2, password3, etc]
i want to ask the user for a username and password input and check if they are in the corresponding lists. However i cant work out how to do it without someone being able to login using their username and someone else's password.
My current code is:
def Login():
usernames = [username1, username2, username3]
passwords = [password1, password2, password3]
user = input("Please enter your username: ")
pw = input("Please enter password: ")
x = 0
for x in range(len(usernames)):
if user == usernames[x] and pw == passwords[x]:
print("Login Successful")
elif user == usernames[x] and pw != passwords[x]:
print("Password does not match")
Login()
else:
print("User not recognised")
Login()
x = x + 1
I want to be able to check what position the username they gave me is in the list and then look for that position in the passwords list and if that password is the one they gave, they can login.
Thank you!
You can use zip to iterate over your list. And use enumerate if you need to find the position.
Demo:
def Login():
usernames = ['username1', 'username2', 'username3']
passwords = ['password1','password2', 'password3']
user = input("Please enter your username: ")
pw = input("Please enter password: ")
for i, x in enumerate(zip(usernames, passwords)):
if user == x[0] and pw == x[1]:
print("Login Successful")
print("Index Position ", i)
elif user == usernames[x] and pw != passwords[x]:
print("Password does not match")
print("Index Position ", i)
Login()
else:
print("User not recognised")
Login()

Python: Calling function through while loop

I'm trying to expand my program to a program that stores login details in a dictionary, and when you're trying to login in, it should ask for your username and password, and if the login details match the ones appended to the dictionary, it would say "You are logged in!", but I cannot seem to call my login() function at all, except the else print statement prints out when I have no login details entered but it doesn't loop back to the menu() like its supposed to, as I put it in a while loop. I think I kind of screwed up my while loops in the main routine but can't seem to get my head around it. Help would be appreciated.
store = {}
def menu():
mode = input("""Hello, below are the modes that you can choose from:\n
##########################################################################
a) Login with login details
b) Register login details
To select a mode, enter the corresponding letter of the mode below
##########################################################################\n
> """).strip()
return mode
def login():
if len(store) > 0 : #user has to append usernames and passwords before it asks for login details
print("Welcome to the login console")
while True:
username = input ("Enter Username: ")
if username == "":
print("User Name Not entered, try again!")
continue
password = input ("Enter Password: ")
if password == "":
print("Password Not entered, try again!")
continue
try:
if store[username] == password:
print("Username matches!")
print("Password matches!")
logged() #jumps to logged function and tells the user they are logged on
break
except KeyError: #the except keyerror recognises the existence of the username and password in the list
print("The entered username or password is not found!")
else:
print("You have no usernames and passwords stored!")
def register(): #example where the username is appended. Same applies for the password
print("Please create a username and password into the password vault.\n")
while True:
validname = True
while validname:
username = input("Please enter a username you would like to add to the password vault. NOTE: Your username must be at least 3 characters long: ").strip().lower()
if not username.isalnum():
print("Your username cannot be null, contain spaces or contain symbols \n")
elif len(username) < 3:
print("Your username must be at least 3 characters long \n")
elif len(username) > 30:
print("Your username cannot be over 30 characters \n")
else:
validname = False
validpass = True
while validpass:
password = input("Please enter a password you would like to add to the password vault. NOTE: Your password must be at least 8 characters long: ").strip().lower()
if not password.isalnum():
print("Your password cannot be null, contain spaces or contain symbols \n")
elif len(password) < 8:
print("Your password must be at least 8 characters long \n")
elif len(password) > 20:
print("Your password cannot be over 20 characters long \n")
else:
validpass = False #The validpass has to be True to stay in the function, otherwise if it is false, it will execute another action, in this case the password is appended.
store[username] = password
validinput = True
while validinput:
exit = input("\nEnter 'end' to exit or any key to continue to add more username and passwords:\n> ")
if exit in ["end", "End", "END"]:
menu()
break
else:
validinput = False
register()
return register
def logged():
print("----------------------------------------------------------------------\n")
print("You are logged in!")
#Main routine
#The main program to run in a while loop for the program to keep on going back to the menu part of the program for more input till the user wants the program to stop
validintro = False
while not validintro:
chosen_option = menu() #a custom variable is created that puts the menu function into the while loop
validintro = True
if chosen_option in ["a", "A"]:
login()
elif chosen_option in ["b", "B"]:
register()
else:
print("""That was not a valid option, please try again:\n """)
validintro = False
That is because after printing "You have no usernames and passwords stored!", you return back to the outer while but never change validintro to false. This causes your while loop to end.
You should either return a value from login to know if there is no user and check that in the while, or from within the login function, in the else part set the global validintro to false(I would recommend the first way.)

Dual password authentication in Python

Been trying out some python as I learnt a bit in school and I've been trying to make a simple login system with password authentication.
The way I want it to work:
get username and password,
ask for password for authentication and if password is not correct then ask again until it gets the right one
this is my code so far:
#online auth
email = input('What is your email address?')
password = input('Enter a password')
passcheck = input('Please re-enter password for confimation')
while passcheck != password:
input('Please re-enter password for confirmation')
else: print("A confirmation code has been emailed to you")
When I run the program it asks for the email and username properly and then I get the confirmation question. If i enter the same password as the one i inputted in the first place it proceeds to the else statement. If i enter the wrong one it ends a never ending loop of reenter the password, even if i input the correct one.
I know that the while loop created an infinite loop but I cant find any good way to end it.
You could do something like
email = input('What is your email address?')
password_input = False
while not password_input or pass_check != password:
password = input('Enter a password')
pass_check = input('Please re-enter password for confimation')
password_input = True
print("A confirmation code has been emailed to you")
Just solved with the help of my friend:
#online auth
email = input('What is your email address?')
password = input('Enter a password')
passcheck = input('Please re-enter password for confimation')
while passcheck != password:
passcheck = input('Please re-enter password for confirmation')
else: print("A confirmation code has been emailed to you")
a good way to end a loop is to either use a for, or a counter variable
for index in range(0,5):
password = input('Enter a password')
pass_check = input('Please re-enter password for confimation')
if pass_check == password :
print("A confirmation code has been emailed to you")
index=65532
else :
print("The passwords do not match, try again.")
if index != 65532 :
print("too many attempts, if you want to retry, please restart the program")
note : the 65532 is not special, it's just out of range, so you exit the for.

Resources