My program is meant to show people their password for apps when they enter it, but for some reason its not showing all the app names they have entered in the line print('''here are your apps, {} which ones information do you want to view'''.format(a[0]) here if the user has previously entered their information for YouTube, Facebook etc., it should print out print('''there are your apps, YouTube, Facebook
which ones information do you want to view'''.format(a[0]))
and then the user will type which one and it will show their password for it.
vault_apps = []
users_passwords = ""
def existing_apps():
if len(vault_apps) < 1:
print('''you have currently 0 app and passwords stored on your account''')
locker_menu_func()
else:
for a in vault_apps:
print('''here are your apps, {}
which ones information do you want to view'''.format(a[0]))
break
while True:
users_passwords = input('''
''')
if users_passwords == "":
print('''Please enter a valid answer''')
else:
for a in vault_apps:
if users_passwords in a:
print('''{}
password: {}'''.format(users_passwords, a[1]))
def store_apps():
while True:
app_name = input('''What is the name of the website/app your are adding?
''')
if 0 < len(app_name) < 16:
break
elif app_name == "":
print("Please enter an answer")
while True:
app_password = input('''What is the password of your {} account?
'''.format(app_name))
if app_password == "":
print("Please enter an answer")
else: vault_apps.append([app_name, app_password])
break
while True:
add_app = input('''would you like to add another app and password, yes or no
''')
if add_app.lower() == "no":
locker_menu_func()
elif add_app.lower() == "yes":
store_apps()
else:
print("please enter a proper answer")
def locker_menu_func():
print('''You have opened the locker,
Please select what you would like to do,''')
locker_menu_var = input('''Press: \n1) find your existing passwords \n2) save a new password for your apps
3) see a summary of your password locke \n4) exit password locker successfully
---------------------------------------------------------------------------------
''')
print('''----------------------------------------------------------------''')
while True:
if locker_menu_var == "1": existing_apps()
if locker_menu_var == "2": store_apps()
locker_menu_func()
break
locker_menu_func()
you are breaking on the very first found app here:
..
for a in vault_apps:
print('''here are your apps, {}which ones information do you want to view'''.format(a[0]))
break
You are not checking for what if the user enters an invalid app name, to which the password does not exist here:
..
for a in vault_apps:
if users_passwords in a:
print('''{}password: {}'''.format(users_passwords, a[1]))
You need to put a check for invalid app names as well:
..
if any(app_name in sl for sl in vault_apps):
You need to put a quit statement in there for if a user does not want to continue further:
..
app_name = input("Enter the app name to view its password or Q to quit: ")
if app_name.lower() == "q" : exit("Thank you, see you again!")
Hence:
def existing_apps():
if len(vault_apps) < 1:
print("you have currently 0 app and passwords stored on your account")
locker_menu_func()
else:
print("here are your apps, {}".format([str(x[0]) for x in vault_apps]))
while True:
app_name = input("Enter the app name to view its password or Q to quit: ")
if app_name.lower() == "q" : exit("Thank you, see you again!")
else:
if any(app_name in sl for sl in vault_apps):
for a in vault_apps:
if app_name in a: print("{} password: {}".format(app_name, a[1]))
else: print("Invalid app name!")
OUTPUT:
What is the name of the website/app your are adding?facebook
What is the password of your facebook account?face123
would you like to add another app and password, yes or noyes
What is the name of the website/app your are adding?stackoverflow
What is the password of your stackoverflow account?stack123
would you like to add another app and password, yes or nono
You have opened the locker,
Please select what you would like to do,
Press:
1) find your existing passwords
2) save a new password for your apps
3) see a summary of your password locke
4) exit password locker successfully
---------------------------------------------------------------------------------
1
----------------------------------------------------------------
here are your apps, ['facebook', 'stackoverflow']
Enter the app name to view its password: stackoverflow
stackoverflow password: stack123
Enter the app name to view its password: facebook
facebook password: face123
Enter the app name to view its password: myspace
Invalid app name!
Enter the app name to view its password or Q to quit: q
Thank you, see you again!
The problem is in your existing_apps method. You are iterating over vault_apps but you are breaking once you have printed the first value.
I've added a modification where we get the list of names using a list comprehension, join it using join() and then print the values.
Note also a nice formatting trick where you can use f"{some_variable}" instead of "{}".format(variable)
def existing_apps():
if len(vault_apps) < 1:
print('''you have currently 0 app and passwords stored on your account''')
locker_menu_func()
# PLEASE LOOK AT THE BELOW PORTION
else:
app_names = [x[0] for x in vault_apps]
app_names_pretty = ", ".join(app_names)
print(f'here are your apps, {app_names_pretty} | which ones information do you want to view')
# END OF MODIFICATION
while True:
users_passwords = input()
if users_passwords == "":
print('''Please enter a valid answer''')
else:
for a in vault_apps:
if users_passwords in a:
print('''{}password: {}'''.format(users_passwords, a[1]))
Related
I am really new to programming and I am given an exercise on creating a login system using text files. The thing is I got really confused about my codes, the login system contains two roles which are admin and customers, and customers are divided into registered and unregistered customers. Admins and registered customers are supposed to directly login into the system whereas unregistered customers are required to create a new account. Also, we are not allowed to use global variables or imports. I apologize if the codes are absolute chaos.
Here is my code:
#Role selection
role = int(input("Select your role: [Admin = 1, Customer = 2]"))
#Admin login
def adminLogin():
if(role == 1):
adminUsername = input("Enter your username: ")
adminPassword = input("Enter your password: ")
for line in open("adminLoginDetails.txt","r").readlines():
login_info = line.split
if (adminUsername == login_info [0] ) and (adminPassword == login_info[1]):
print("You have successfully logged in!")
else:
print("Invalid username or password, please try again.")
#Customer registration
else:
def cusRegistration():
registration = input("Are you a registered customer? [Yes/No]")
if (registration == "No"):
cusUsername = input("Enter your username: ")
cusPassword = input("Enter your password: ")
file = open("customerDetails.txt","a")
file.write(cusUsername)
file.write(" ")
file.write(cusPassword)
file.write("\n")
file.close()
if cusRegistration():
print("You have successfully created an account!")
#Customer Login
def cusLogin():
if (registration == "Yes"):
cusUsername = input("Enter your username: ")
cusPassword = input("Enter your password: ")
for line in open("customerDetails.txt","r").readlines():
loginInfo = line.split()
if (cusUsername == loginInfo[0]) and (cusPassword == loginInfo[1]):
print ("You have successfully logged in!")
else:
print("Invalid username or password, please try again.")
You need to actually run your functions:
def do_something():
print('something')
Won't run. You need to also use this:
do_something()
In your case:
if role == 1:
adminLogin()
etc
In your code given above, you need to pull your check for roll outside the methods that use them. Currently, nothing is asking your methods to execute.
role = int(input("Select your role: [Admin = 1, Customer = 2]"))
if role == 1:
adminLogin()
if role == 2:
cusLogin()
# etc
my program is for an assignment to make a password vault, so the user makes an account and enter the password vault, he then adds apps and passwords and views it, The problem is that it also has to print summaries but when the user has no entered app and passwords it dosnt tell them they dont have any.
code for the summary>>
def app_summary():
while True:
if len(vault_apps) < 1:
print('''there is no summary of your acount as,
you currently have 0 apps and passwords stored on your account''')
else: print('''You have {} app and its information stored'''.format(len(vault_apps)))
print('''Your longest password is charecters''', max(len(a) for a in vault_apps))
print('''Your shortest password is charecters''', min(len(a) for a in vault_apps))
goback_menu()
break
as you can see if there is < than one app stored it should print out ('''there is no summary of your acount as,
you currently have 0 apps and passwords stored on your account''') but instead i get this error: max(len(a) for a in vault_apps))
builtins.ValueError: max() arg is an empty sequence
Full code--->
vault_apps = []
users_passwords = ""
username = ""
vault_password = ""
def exit_code(): #This funnction exits the code, and is made into a function as many times through the program I need to exit the code, and now I can just call multiple times through this unction
while True:
print('''\n\n\n\nYou have succesesfuly and safely logged out of password locker
Goodbye!''')
exit() #this is a function for exit it exits the code, but on wing101 it takes you to an exit page which is made by the program called 'sitebulletins'
def goback_menu(): # this code allows the user to go to the main menue of the vault, and also exit at the same time, it was made so instead of always typing the main menue i can call it
goback = input('''Would you like to go back to the main menu or exit the code?, answer with
yes, or exit
''')
if goback == "yes":
locker_menu_func()
elif goback == "exit":
print("okay")
exit_code()
else: print('''please enter yes, or no''')
def existing_apps(): #this function correspons, to the main menu when the user wants to viw their stored apps and passwords, and if the user has none it asks them if they would like to go back to the menu to add some
if len(vault_apps) < 1:
print('''you have currently 0 app and passwords stored on your account''')
goback_menu()
else:
app_names = [x[0] for x in vault_apps] #this displays the stored apps, that the user has entered, if he has any
app_names_pretty = ''' this is for the join attribute which joins the strings within the variables, making them easier to format
'''.join(app_names)
print(f'''Here are the apps which you have stored information on,
------------------
{app_names_pretty}
------------------
which apps information do you want to view''') #I have used f-string as it is better than a format statment, as we are printing a list, i can print with no additional brackets and can be manipulated easier to look nuice
while True:
users_passwords = input()
if users_passwords == "":
print('''Please enter a valid answer''')
else:
for a in vault_apps: #if a (the app information the user is looking for is in thevault_apps list, print it out with the rest of its information like password
if users_passwords in a:
print('''{}password: {}'''.format(users_passwords, a[1]))
while True:
more_apps = input('''press,
1) to see the information of your other apps
2) to return to the main menu
3) to exit the code
''')
if more_apps == "1": existing_apps
if more_apps == "2": locker_menu_func()
if more_apps == "3": exit_code()
else:
print('''please input a valid answer''')
break
def store_apps():
while True:
app_name = input('''What is the name of the website/app you are adding?
''')
if 0 < len(app_name) < 16:
break
elif app_name == "":
print("Please enter an answer")
while True:
app_password = input('''What is the password of your {} account?
'''.format(app_name))
if app_password == "":
print("Please enter an answer")
else: vault_apps.append([app_name, app_password])
addapp()
break
def addapp():
add_app = input('''would you like to add another app and password, yes or no
''')
if add_app.lower() == "no":
locker_menu_func()
elif add_app.lower() == "yes":
store_apps()
else:
print("please enter a proper answer")
def app_summary():
while True:
if len(vault_apps) < 1:
print('''there is no summary of your acount as,
you currently have 0 apps and passwords stored on your account''')
else: print('''You have {} app and its information stored'''.format(len(vault_apps)))
print('''Your longest password is charecters''', max(len(a) for a in vault_apps))
print('''Your shortest password is charecters''', min(len(a) for a in vault_apps))
goback_menu()
break
def locker_menu_func():
print('''
You have opened the locker,
Please select what you would like to do,''')
locker_menu_var = input('''Press: \n1) find your existing passwords \n2) save a new password for your apps
3) see a summary of your password locker \n4) exit password locker
---------------------------------------------------------------------------------
''')
print('''----------------------------------------------------------------''')
while True:
if locker_menu_var == "1": existing_apps()
if locker_menu_var == "2": store_apps()
if locker_menu_var == "3": app_summary()
if locker_menu_var =="4": exit_code()
break
print("------------------------------------------------------------------------")
print('''Welcome to password Locker, a place where you can
store all your passwords to easily enter your precious accounts without
hassle.''')
print("------------------------------------------------------------------------")
print('''First lets make an account,''')
while True:
first_name = input('''What is your first name?
''')
if first_name.isdigit(): #isdigit, detects if there
print("Please enter a valid answer, No nubers shoud be present")
elif first_name == "":
print("Please enter an answer")
else:
break
while True:
sur_name = input('''What is your surname?
''')
if sur_name.isdigit(): #isdigit detects if the
print("No numbers")
elif sur_name == "":
print("Please enter an answer")
else:
break
def login_originup1(username, vault_password):
print(''' Welcome to password vault,
You can either login or create a New account''')
while True:
login_orsignup1 = input(''' Press \n1) to Log in
:''')
if login_orsignup1 == "1":
while input('''--------------------------------------------------------
What is your username: ''') != username:
print("Incorrect username")
while input("What is your password: ") == vault_password:
print('''-----------------------------------------------------------
''')
locker_menu_func()
break
else:
print("Incorrect password")
#Main Routine
print('''------------------------------------------------------------------------''')
print('''Welcome, {} {}
what would you like your username to be, it should be something
memorable and no longer than fifteen characters long, '''.format(first_name, sur_name))
while True:
username = input("")
if 0 < len(username) < 16:
print('''Nice, username''')
break
elif username == "":
print("Please enter an answer")
else:
print('''Your username should be a maximum of 15 charecters, ''')
print('''-------------------------------------------------------------------------''')
while True:
vault_password = input('''Now it's time to setup a password for your locker, It should be between 4
and 10 charecters long,
''')
if len(vault_password) > 4 and len(vault_password) < 11:
print('''{}, is locked in thanks for joining Password Locker'''.format(vault_password))
break
else:
print("It should be between 4 and 10 charecters long!")
print('''
-------------------------------------------------------------------------------------------''')
login_originup1(username, vault_password)
The indentation of the else: block is wrong, it should be:
else:
print('''You have {} app and its information stored'''.format(len(vault_apps)))
print('''Your longest password is charecters''', max(len(a) for a in vault_apps))
print('''Your shortest password is charecters''', min(len(a) for a in vault_apps))
As a general rule, you could avoid putting else: blocks on the same line, this would avoid such problems when you add lines to them afterwards.
Your indentation is wrong. All your print calls should be in the else block. Also, consider using f-strings and factoring out your generator expressions for the lengths into a separate list:
if not vault_apps:
print('There is no summary of your account as you have no apps and passwords stored.')
else:
lengths = [len(a) for a in vault_apps]
print(f'You have {n_apps} apps and their information stored.')
print(f'Your longest password is {max(lengths)} characters.')
print(f'Your shortest password is {min(lengths)} characters.')
My logins() sub routine will continue to carry out both the else and elif parts after it has found a login and has verified the password. I cant seem to understand why its doing this but is really halting my progress.
enter image description here
def login ():
Username_Input = input("Please enter your username : ")
logins = open("logins.csv","r")
List_Information = list(csv.reader(logins))
for x in List_Information:# loops through all lists
if x[0] != Username_Input :
print("Username not found please register ")
register ()
else:
Password_Input = input("Username found please enter your password : ")
for x in List_Information:
if x[1] == Password_Input :
print("Loged in lets get this game going. ")
game()
else :
print("nope sorry password not found lets go back to the menu : ")
Menu()
After it has found the correct password it will continue going through the List_information after calling game(). The call to game() would not stop the looping and thus it finds the next user from the List_information and say that the password was wrong.
You should be finding the correct entry from the List_information (based on the username) and the check the password against that entry. Now you are basically only comparing the first element in the List_information.
Something like this:
user = None
for x in List_information:
if x[0] == Username_input:
user = x
if user == None:
print("Username not found please register ")
register ()
else:
Password_Input = input("Username found please enter your password : ")
if user[1] == Password_input:
game()
else:
Menu()
I'm making login/signing section for my code. I have 2 issues with it. I need help:
First question Yes or No functions well until other character entered. While loop is not accepted for some reason. How to get back to beginning until Y or N entered?
I would like to store dict with usernames and passwords as CSV file sorted in two columns not rows. How to do it.
Thanks
Here is the code....
# CREATING START DICTIONARY
users = {"guest": "guestpass", "admin": "adpass"}
status = input("\rAre you a registered user? Y / N? ").upper()
while status != "Y" and status != "N":
print ("Please enter Y or N")
# NEW USER
if status == "N":
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
print("Login name already exist! Please, choose another one.\n")
else:
createPass = input("Create password: ")
retypePass = input("Retype password: ")
while True:
if createPass != retypePass:
print("\nPassword error!\n")
else:
users.update({createLogin : createPass})
print("\nNew user created! Welcome to ARR!\n")
break
import csv
writer = csv.writer(open('UsersFile.csv', 'wb'))
for key, value in users.items():
writer.writerow([createLogin, createPass])
# LOGIN EXISTING/NEW USER
elif status == "Y":
while True:
loginName = input("Enter login name: ").lower()
if loginName not in users:
print("User doesn't exist! Please enter existing name or sign-in.")
print("----------------------------------------------------------")
else:
passw = input("Enter password: ")
# LOGIN MATCHES PASSWORD
if loginName in users and passw != users.get(loginName):
print("Wrong password! Please enter username and password again!")
else:
print("Login successful!\n")
break
1) In your y/n while loop you are missing a tab to indent the print statement.
2) https://docs.python.org/2/library/csv.html
Some issues I see so far:
Indentation. print ("Please enter Y or N") should be indented relative to the while statement on the previous line.
Also, the statement if createLogin in users and the following else statement should probably be indented one more level, if they are meant to be within the if status == 'N' statement.
Import statement. Generally, things like import csv would be at the top of the file. Try moving it there and see if it helps.
Hi. I am trying to make a program that is able to create users and then log them in. Once you're logged in you can change your password. What I can't seem to figure out is how to get it to change your password after you logged in, using only your old password. I can get it to work by inputting your account name, but that's not the point.
Do any of you have any idea of how to fix this problem, I am open to suggestions :)
import json
with open("login_data.txt", "r") as login_file:
try:
users = json.load(login_file)
except:
users = {}
status = ""
def Display_Menu():
status = input("Are you a registered user? (y/n)? Press q to quit: ")
if status == "y":
Old_User()
elif status == "n":
New_User()
elif status == "passwd":
Change_Passwd()
elif status == "q":
skriva = open("login_data.txt", "w")
json.dump(users, skriva)
return status
def New_User():
Create_Login =input("Create login name: ")
if Create_Login in users:
print ("Login name already exist!")
else:
Create_Password =input("Create password: ")
users[Create_Login] = Create_Password
print("New User created!")
def Old_User():
login =input("Enter login name: ")
Password =input("Enter password: ")
if login in users and users[login] == Password:
print("Login successful!")
print(users[login])
status = input("Wanna quit, change pass, och logout?")
if status == "passwd":
Change_Passwd()
elif status == "logout":
Display_Menu()
elif status == "q":
skriva = open("login_data.txt", "w")
json.dump(users, skriva)
return status
else:
print("User doesn't exist or wrong password!")
def Change_Passwd():
oldpass =input("Old password: ")
if oldpass in users:
Create_Password =input("New password: ")
users[oldpass] = Create_Password
if Create_Password == input("Confirm password: "):
print("Password changed!")
else:
print("User authorization failure")
users[create_Login] = oldpass
else:
print ("No password match!")
while status != "q":
status = Display_Menu()
A example of a account file " { "halo": "molly"} "
The minimal change would be to save the currently logged in user to a global variable in Old_User(). Then, when Change_Passwd is called, you can go back to that variable to determine which user you're dealing with. Here's the changes you'd make to Old_User. I'll leave the changes to Change_Passwd up to you to implement.
current_user = None # Declare global variable for saving logged in user
def Old_User():
global current_user # Indicate that we're going to modify the global variable in the local scope
login =input("Enter login name: ")
Password =input("Enter password: ")
if login in users and users[login] == Password:
print("Login successful!")
print(users[login])
current_user = login # Save the logged in user.
...
I should also add that you'd be better served using classes for this. Trying to maintain state (like who the current user is) using global variables is not very scalable and can get confusing pretty quickly. Having classes representing users and active sessions would make things easier.