How do i fix my while loop - python

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()

Related

iam getting an error on when i chose option 2 for login, with NameError: name 'profiles' is not defined on line 81

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.

Why won't my print statements show up in my elif block?

I know there is probably a simple solution to this, but the text I wrote under the elif sections in userName and passWord will not print when a user successfully logs in. Please help!
def userName():
username = "kate"
userInput = input('Please enter your username:\n')
while userInput != username:
if len(userInput) == 0:
print("Your username can not be blank, please try again!\n")
userInput = input('Please enter your username.\n')
elif userInput == username:
print("Welcome back, " + username)
print("")
break
else:
print("Sorry, that username is not in our system. Please try again!\n")
userInput = input('Please enter your username.\n')
def passWord():
password = "stags"
passInput = input("Please enter your password:\n")
while passInput != password:
if len(passInput) == 0:
print("Your password can not be blank, please try again!\n")
passInput = input("Please enter your password.\n")
elif passInput == password:
print("You have successfully logged in!\n")
break
else:
print("Sorry, your password is invalid. Please try again!")
passInput = input("Please enter your password.\n")
def main():
print("Hello, let's get started!")
print("")
userName()
passWord()
main()
This was pointed out in the comments above, but if you change
while userInput != username:
and
while passInput != password:
to
while True:
it should work just fine. Then it forces your code to hit the elif statement rather than breaking the loop before printing what you want to say.
In python indentation indicates where a code block starts and begins. So in your while loop in passWord() your if..elif..else must be indented exactly one tab in eg.
while passInput != password:
if len(passInput) == 0:
print("Your password can not be blank, please try again!\n")
passInput = input("Please enter your password.\n")
elif passInput == password:
print("You have successfully logged in!\n")
break
else:
print("Sorry, your password is invalid. Please try again!")
passInput = input("Please enter your password.\n")
Notice how the indentation always goes one tab in for each code block you want to create.

How to get "Correct enter the maze" without getting "sorry, please try again"

password = "nothing"
tries = 0
while password != "secret":
tries = tries + 1
password = input("What is the secret password? ")
print("sorry, please try again. ")
if tries == 3:
print("You have been locked out")
exit()
print("Correct! Enter the maze!")
when i write the correct password i get this in return
What is the secret password? secret.
sorry, please try again.
Correct! Enter the maze
Python has no do-while, so one of ways to do similar thing is
password = ""
tries = 0
while True:
password = input("What is the secret password? ")
if password == "secret":
break
print("sorry, please try again. ")
tries += 1
if tries == 3:
print("You have been locked out")
exit()
print("Correct! Enter the maze!")
You can use this code:
password = "nothing"
tries = 0
while password != "secret":
tries = tries + 1
password = input("What is the secret password? ")
if password == "secret":
break
else:
print("sorry, please try again. ")
if tries == 3:
print("You have been locked out")
exit()
print("Correct! Enter the maze!")
If you do not want the password to be seen, you can use the following library
getpass()
example:
import getpass
p = getpass.getpass(prompt='What is the secret password? ')
if p.lower() == 'secret':
print('Correct! Enter the maze!')
else:
print('sorry, please try again.')

password vault issues, code not following if statements

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.')

Adding an if statement to a while loop

The premise of this code is to ask for a name, with a maximum of 3 attempts.
password = 'correct'
attempts = 3
password = input ('Guess the password: ')
while password != 'correct' and attempts >= 2:
input ('Try again: ')
attempts = attempts-1
if password == 'correct': #Where the problems begin
print ('Well done')
I can only enter the right password for the first attempt to return 'well done.' On the other two attempts, it will return as 'try again.' How can I get it to return well done, if entered on any of the attempts?
If you want to try again, then you need to capture that value.
password = input ('Try again: ')
Otherwise, the while loop never stops.
Additionally, Python has while-else, which could help you debug the issue
while password != 'correct' and attempts >= 2:
password = input ('Try again: ')
attempts = attempts-1
else:
print('while loop done')
if password == 'correct': #Where the problems begin
print ('Well done')
Or
attempts = 3
password = input('Enter pass: ')
while attempts > 0:
if password == 'correct':
break
password = input ('Try again: ')
attempts = attempts-1
if attempts > 0 and password == 'correct':
print ('Well done')
attempts = 3
while attempts > 1:
password = input("Guess password")
if password == "correct" and attempts > 2:
print("Well done")
break
else:
print("try again")
attempts = attempts - 1
This is a fun way to do it, instead of using a counter, you can create a list with three elements and the while test makes sure there are still elements left:
password,wrong,right = 'nice',['Wrong']*3,['you got it!']
while len(wrong)>0 and len(right)>0:
right.pop() if input('guess:')==password else wrong.pop()

Categories

Resources