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.)
Related
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!
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.
When someone enters an incorrect password I want to loop user input, but if they get it correct I want it to stop looping.
return False I need a function for return but I don't know where or what to make it as
while True:
userInput = input("Pass:")
if userInput == password:
print("Correct, welcome to Fahuk Console.")
print("Type \"help\" for a list of commands.")
userInput = input("-")
else:
print("Incorrect password.") ```
I want to be able to enter a correct password and not have it ask me again
Use this code:
while True:
userInput = input("Pass:")
if userInput == password:
print("Correct, welcome to Fahuk Console.")
print("Type \"help\" for a list of commands.")
userInput = input("-")
break
else:
print("Incorrect password.")
Use the break keyword
while will continue to execute the code it's given until the condition placed after it is false or until break is used to immediately exit the loop.
Try this:
while input('Please enter your password:') != password:
print('Incorrect password.')
print('Correct, welcome to Fahuk Console.')
# ...
Or if you want to use while True, this:
while True:
if input('Please enter your password') == password:
break
print('Incorrect password.')
print('Correct, welcome to Fahuk Console.')
# ...
(When you store a real password, you shouldn't store the password itself, but instead a difficult-to-reverse hash of that password. You might import hashlib and then instead of comparing input() to the password, you might compare hashlib.sha256(input()).hexdigest() to the password's SHA-256 hash.)
Simplest way would be to use a break condition. Loops iterate over a block of code until an expression is false. Since your expression is always true, break would need to be used to terminate the current iteration/loop.
while True:
userInput = input("Pass:")
if userInput == password:
print("Correct, welcome to Fahuk Console.")
print("Type \"help\" for a list of commands.")
userInput = input("-")
break
else:
print("Incorrect password.") ```
I have made a program that stores login details that you have entered and allows you to login it with it into the main part of the menu. Everything was working fine when all the data types were strings, for example; modea = input("Etc") to allow the user to select options by entering number inputs that correspond to the option, e.g "2", it should call its assigned function as it fulfills the if modea == 2 statement, but if I try to change string to integer data type, for example modea = int(input("Etc")), even if I were to enter an expected input, the loop would never stop and continue running as if I entered nothing, contrary to simply using modea = input("etc") where it treats everything as a string, and it would still accept number input and carry out its assigned action, but not if the data type is an integer?
I added full code here for it to make more sense, which most can be ignored as it runs as intended, but I can't seem to get my head around whats going on with the logged()function part of the code where I attempted to get modea = int(input("etc")) to work by terminating its loop when the if statements are fulfilled, but it just continues on looping as if everything is null. Help would be appreciated.
#import modules
import time
import sys
import re
#Initialise variables that could help with error handling
name = ""
mode = ""
username = ""
password = ""
addusername = ""
addpassword = ""
exit = ""
modea = ""
new_app = ""
new_pass = ""
quit = ""
#Dictionary to store more than one set of login details
vault = {}
#Lists to store website names and passwords
appvault = []
passvault = []
#FIRST MENU AND REGISTERING LOGIN DETAILS -----------------------------------------------------------------------------------------------------------------------------------------
def menu(): #The menu function is the 1st menu that asks the user to either register their login details or to login with existing login details saved into the vault dictionary
print("--------------------------*ENTERING THE MAIN MENU*-----------------------------------\n") #triple """ used to effectively format the menu
mode = input(str("""Hello {}, below are the modes that you can choose from:\n
##########################################################################
a) Login with username and password
b) Register as a new user
To select a mode, enter the corresponding letter of the mode below
##########################################################################\n
> """.format(name))).strip() #greets user and removes any white space
return mode #returns the input
def login(username, password): #The login function is where the user logins in with existing registered details in the vault dictionary
if len(vault) > 0 : #user has to append usernames and passwords before it asks for login details
print("Welcome {} to the login console".format(name))
noloop = True #Starts a loop if True will begin looping
while noloop:
addusername = input("Please enter username: ")
if addusername == "":
print("Username not entered, try again!")
continue #returns to the beginning of the while loop if null
addpassword = input("Please enter password: ")
if addpassword == "":
print("Password not entered, try again!")
continue #returns to the beginning of the while loop if null
try:
if vault[addusername] == addpassword: #If the username and password match with the login details appended into the dictionary, it will count as matching details.
print("Username matches!")
print("Password matches!")
print("Logging into password vault...\n")
noloop = logged() #jumps to logged function and tells the user they are logged on
return noloop #to return the noloop depending on users option (True or False)
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!") #When the user selects option A before adding any login details to the dictionary
return True #returning to the start of the loop when the else statement is printed
def register(): #example where the username is appended. Same applies for the password
global username #initialises global variables
global password
print("Please create a username and password into the password vault.\n")
while True:
validname = True #whileloop will loop the username variable and while True it runs the loop
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(): #handles usernames with no input, contain spaces between them or have symbols in them.
print("Your username cannot be null, contain spaces or contain symbols \n")
elif len(username) < 3: #any username with less than 3 characters is rejected and looped back
print("Your username must be at least 3 characters long \n")
elif len(username) > 30: #any username with more than 30 characters is rejected and looped back
print("Your username cannot be over 30 characters long \n")
else:
validname = False #whileloop is False will mean the loop will break and proceed onto asking password
validpass = True #whileloop will loop the password variable and while True it runs the loop
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(): #handles null input passwords, passwords that contain spaces or symbols
print("Your password cannot be null, contain spaces or contain symbols \n")
elif len(password) < 8: #passwords that are less than 8 characters long are rejected and loops back
print("Your password must be at least 8 characters long \n")
elif len(password) > 20: #passwords that are more than 20 characters long are rejected and loops back
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.
vault[username] = password #the appending process of username and passwords to the dictionary
validinput = True #whileloop asking for the user if they want to quit or add more login details
while validinput:
exit = input("\nDo you want to register more usernames and passwords? Enter 'end' to exit or any key to continue to add more username and passwords:\n> ")
if exit in ["end", "End", "END"]: #if input matches these conditions, the loop will then break and thus jump back to the main menu
return #returns outputs to the called function
else:
validinput = False #if user decides not to quit and to add more login details, then register is called and the process of asking for login input repeats
register()
return register #returns login details to the function
#LOGGED ONTO THE PASSWORD AND WEBSITE APP ADDING CONSOLE------------------------------------------------------------------------------------------------------------------------
def logged(): #The logged function is the 2nd menu where the user is able to access after logging in with their registered login details
print("-----------------------------*ENTERING THE PASSWORD VAULT MENU*-----------------------------------\n")
print("You are logged in, welcome to the password vault console.")
keeplooping = True #whileloop that is True will keep the menu in a loop
while keeplooping:
try:
modea = int(input("""Below are the options you can choose from in the password vault console:
##########################################################################\n
1) Find the password for an existing website/app
2) Add a new website/app and a new password for it
3) Summary of the password vault
4) Exit
##########################################################################\n
> """))
except ValueError:
print("Please enter a valid option!")
if modea == 1: #if the user enters 1 as instructed, then they have decided to choose to find existing apps and passwords
viewapp() #viewapp function is called
elif modea == 2: #if user enters 2 as instructed, then they have decided to add new app/websites and the passwords for it
addapp() #addapp function is called
elif modea == 3: #if the user enters 3 as instructed, then they have decided to look at the summary of passwords entered so far
summary() #summary function is called
elif modea == 4: #if the user enters 4 as instructed, then they have deicided to quit the entire program. All loops stop and program ends with print statement saying "Goodbye"
keeplooping = False
print("*Exiting program*\n")
time.sleep(2)
print("############################################################")
print("Goodbye user and thanks for using the password vault program")
print("############################################################")
return keeplooping
else:
print("That was not a valid option, please try again: ")
validintro = False
def viewapp(): #The viewapp function is the 1st option of the password and vault menu that allows the user to view the app/websites and passwords stored so far
if len(appvault) > 0: #The website/apps and passwords are only shown once the user has entered a set of the info, otherwise no info will be shown
print("""Below are the details of the website/apps and passwords stored so far:
(NOTE: Websites/apps and passwords are shown in order of being appended; 1st password is for 1st website, etc...\n""")
for app in appvault:
print("Here are the website/app you have stored:")
print("- {}\n".format(app)) #Website/app is printed out here
if len(passvault) > 0 : #The website/apps and passwords are only shown once the user has entered a set of the info, otherwise no info will be shown
for code in passvault:
print("Here are the password you have stored for the websites/apps: ")
print("- {}\n".format(code)) #The passwords are printed out here
else:
print("You have no apps or passwords entered yet!")
def addapp():
while True:
validapp = True
while validapp:
new_app = input("Enter the new website/app name: ").strip().lower()
if len(new_app) > 20: #if the user enters a website with more than 20 characters, it is rejected and loops back and asks for input again
print("Please enter a new website/app name with no more than 20 characters: ")
elif len(new_app) < 1: #if the user enters nothing, program loops back and asks for input again
print("Please enter a valid new website/app name: ")
else:
validapp = False
appvault.append(new_app)
validnewpass = True
while validnewpass:
new_pass = input("Enter a new password to be stored in the passsword vault: ").strip()
if not new_pass.isalnum(): #checks if the entered username has spaces, or symbols or is a null input, which would be rejected and the program will loop back
print("Your password for the website/app cannot be null, contain spaces or contain symbols \n")
elif len(new_pass) < 8: #the password must be at least 8 characters long to be accepted as valid
print("Your new password must be at least 8 characters long: ")
elif len(new_pass) > 20: #the password must not exceed 20 characters, otherwise it would be rejected and will loop back
print("Your new password cannot be over 20 characters long: ")
else:
validnewpass = False
passvault.append(new_pass)
validquit = True
while validquit:
quit = input("\nDo you want to enter more websites/apps and passwords? Enter 'end' to exit or any key to continue to add more website/app names and passwords for them: \n> ")
if quit in ["end", "End", "END"]:
return
else:
validquit = False
addapp()
return addapp
def summary(): #The summary function is a print statement of how many password have been stored, the passwords with the longest or shortest characters are also displayed
if len(passvault) > 0: #The user must have entered at least 1 password before the summary option can be viewed
print("----------------------------------------------------------------------")
print("Here is a summary of the passwords stored in the password vault:\n")
print("The number of passwords stored so far:", len(passvault)) #len counts the amount of passwords stored in the passvault list
print("Passwords with the longest characters: ", max(new_pass for (new_pass) in passvault)) #max finds the passwords appended in the passvault list with the longest password
print("Passwords with the shortest charactrs: ", min(new_pass for (new_pass) in passvault)) #min finds the passwords appended in the passvault list with the shortet password
print("----------------------------------------------------------------------")
else:
print("You have no passwords entered yet!")
#Main routine
print("Welcome user to the password vault program")
print("In this program you will be able to store your usernames and passwords in password vaults and view them later on.\n")
validintro = False
while not validintro:
name = input(str("Greetings user, what is your name?: ")).lower().strip()
if not re.match("^[a-z]*$", name):
print("Your name must only contain letters from a-z: ")
elif len(name) < 1:
print("Please enter a name that is valid: ")
elif len(name) > 30:
print("Please enter a name with no more than 30 characters long: ")
else:
validintro = True
print("Welcome to the password vault program {}.\n".format(name))
#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()
validintro = False
if chosen_option in ["a", "A"]:
validintro = not login(username, password)
elif chosen_option in ["b", "B"]:
register()
else:
print("""That was not a valid option, please try again:\n """)
validintro = False
You have an indentation error.
Your while keeplooping: loop in logged() only contains the try / except block so it keeps looping that over and over. I think you want to indent the if statements below it.
Edit based on comment:
When you try/except reaches except it prints the statement and then keeps on going. You haven't included anything in the except statement to tell the while loop to start again. Since the assignment of modea failed, it isn't assigned and results in an error when you try to reference it. If you want to try another input when the user puts in a bad value you can use continue:
except ValueError:
print("Please enter a valid option!")
continue
This will cause the whole instruction string to print again — there may be a better logic, but at least this will prevent the error.
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.