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.')
Related
anyone to help me with a serious problem am facing here, its about python, login, signup, and password reset for my assignment
am having trouble with the login code, it keeps on throwing errors ill share the code here for the two files.....
this is the signup code
import datetime
from task2 import *
# collecting data and storing for profile use
profiles = []
def signUp():
Customer_name = input("Please enter your name : ")
phone_number = input("Please enter your mobile number : ")
pwd = input("Please enter your Password : ")
confirm_Pwd = input("Please confirm your Password : ")
dob = input("please Enter your Date of Birth # DD/MM/YY (No Space) : ")
# checking if the phone number is correct
if phone_number[0] != 0 and len(phone_number) != 10:
print("You have enter an invalid Phone number format")
print("Please try again:")
return False
# check password last digit is numeric
if pwd[-1].isnumeric() == False:
print("Password should end with number")
print("Please try again:")
return False
# checking the presence of specific special characters in password
character = ['#', '#', '$']
result = [ele for ele in character if (ele in pwd)]
# return false if this character not present
if result == False:
print("Password should include #,# or $")
print("Please try again:")
return False
# check password and confirm password inconsistency
if pwd != confirm_Pwd:
print("Your password are not matching")
print("Please start again:")
return False
# checking date format
out = True
try:
# split the date, month and year using a '/' character
day, month, year = dob.split('/')
# check its compliance with suggested date format
datetime.datetime(int(year), int(month), int(day))
except ValueError:
# if not return false and a confirming messgae
out = False
if (out == False):
print("Date should be in correct format")
print("Please try again:")
return False
# checkin the clint's age
dob_year = dob[-3:]
if (2022 - int(dob_year)) < 21:
print("Your age should be at least 21 year old")
print("Please try again:")
return False
# create a list containing all client gathered data
lst = [Customer_name, dob, phone_number, pwd, confirm_Pwd]
profiles.append(lst)
print("You have successfully signed up")
# the main body
while True:
print("Please enter 1 for sign up.")
print("Please enter 2 for log in.")
print("Please enter 3 for Quite.")
choice = input()
# if choice is 1 creates a new class object before calling the signup function
if choice == "1":
signUp()
# if choice is 2 login method from the login file with profile list
if choice == "2":
loginprofiles()
# if choice is 3 break from loops
if choice == "3":
print("Thank you for using the Application")
break
-----------here is the login file-----------
from task2B import *
def loginprofiles():
# set a flag to count the number of failed logins attempts, initiate it with 0
login_attempt = 0
while (True):
user_name = input("Please enter your username (mobile number) ")
pwd = input("Please enter your password ")
# set login to false to ensure the user is not logged in
login_flag = False
# multiimentional list(profiles)
for list in profiles:
for i in range(0, len(list)):
if list[1] == user_name and list[2] == pwd:
login_flag = True
name = list[0]
# checking for invalid logins
if login_flag == False:
print("You have entered a wrong password")
print("please try again")
login_attempt = login_attempt + 1
# prompt the user with a password reset
if login_attempt == 3:
reset_pass(profiles)
break
else:
# successful login
print("You have successfully signed in ")
print("welcome " + name)
break # break from entire loop
# give more options
while (True):
print("Please enter 1 for resetting the password :")
print("Please enter 2 for sign out")
choice = input()
# if choice is 1 . reset() from task3 is called
if (choice == "1"):
reset(profiles)
if (choice == "2"):
print("you have sucessfuly logged out")
break
Since you don't tell us which script is which or how you execute this code, I'll just make up some names. I'm going to call that first one script.py and assume that its the .py file you execute. I'll call that second one m1.py assuming its an imported module.
Python does not have a truly global namespace. Each module gets a namespace dictionary that is available to that module via globals() and to other modules by import. The first .py file to run is special - its a script whose namespace is named __main__. Other namespaces are named by package and module names.
Assuming script.py is the top level script named __main__, it is not a good place to put variables that need to be found by other modules. So, its not a good place for the profiles list. Assuming that m1.py is imported and it holds the functions that use the profiles list, that's a good place to put profiles = []. The loginprofiles function will automatically find variables in its module's "global" namespace, including profiles. So, move that line to the second module.
Since the main script.py also uses this same variable, it should import m1 and use m1.profiles. That is, reference the namespace that has the profiles variable. Better still, take anything that uses profiles directly and convert it to a function in m1.py. This decouples the main script from the profiles variable and makes long term maintenance easier.
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 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]))
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 am writing a program that asks the user to enter a password. If the password matches the constant I've set it prints out a "successfully logged in message". However if the password is incorrect, it gives the number of guesses left and asks the user to try again. The program should end after 3 incorrect guesses but it keeps on asking even after 3 attempts have been used. I think the problem is in my while loop but I am unsure.
Code:
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD :
ALLOWED = ALLOWED - 1
print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0:
print("You have been locked out")
password = input("Enter again ")
print("You have successfully logged into the system")
main()
Right now you never exit your while loop. To break out of it, use the break keyword.
To exit your program completely, you will need to import sys and sys.exit()
I suggest adding these to your if ALLOWED == 0 statement.
You need to use break to exit the loop, or add a secondary condition, otherwise it will keep going anyway until the password is correct.
So, either:
while (password != PASSWORD) and (ALLOWED > 0):
Or:
if ALLOWED == 0:
print("You have been locked out")
break
The condition password != PASSWORD is not enough to exit the loop (It will exit the loop only if you give the right password). Add the condition also in while (password != PASSWORD and ALLOWED > 0)
Change print("You have been locked out") to sys.exit("You have been locked out") (or otherwise exit the main). Remember to import sys to use sys.exit.
Your while loop requires a correct password to finish, and there is no other way to exit the loop. I suggest a break statement:
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD :
ALLOWED = ALLOWED - 1
print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0:
print("You have been locked out")
break
password = input("Enter again ")
print("You have successfully logged into the system")
You may want to do more research if your program needs to be secure.
Managed to make it work but just making it check if ALLOWED == 0 and if it does print "you are locked out", and if ALLOWED <= 0 then it will not let you go any further.
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD or ALLOWED <= 0:
ALLOWED = ALLOWED - 1
if ALLOWED > 0: print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0: print("You have been locked out")
if ALLOWED < 0:
print("You have been locked out")
password = input("Enter again ")
print("You have successfully logged into the system")
main()
also wrote a different version which seemed easier in my opinion
def main():
USERNAME = "admin"
PASSWORD = "root"
ATTEMPTS = 3
while ATTEMPTS >= 1:
print("You have",ATTEMPTS,"attempts left")
if ATTEMPTS == 0:
break
user = input("Please enter your username:")
password = input("Now enter your password:")
if user == USERNAME and password == PASSWORD:
print("\nYou have successfully logged into the system")
return
else:
print("\nThis user name or password does not exist\n")
ATTEMPTS -= 1
print("you have been locked out.")
main()