I want to print 5 attempts completed if i use all the attempts incorrectly
def user_name_repeat():
for repeat_user_name in range(4):
re_enter_user_name = input("Incorrect username, try again: ")
if re_enter_user_name == "vishesh":
print("Correct user name ur logged in")
break
input_ = input("enter user name: ")
if input_ == "vishesh":
print("Correct user id, you are logged in: ")
elif input_ != "vishesh":
print(user_name_repeat())
Why not wrap the whole thing inside a loop?
for _ in range(5):
input_ = input("enter user name: ")
if input_ == "vishesh":
print("Correct user id, you are logged in")
break
else:
print('Incorrect username, try again')
else:
print('Attempts exhausted')
More info on for/else
Edit: You could also fix up the logic in your own code with something like-
def user_name_repeat():
for repeat_user_name in range(4):
re_enter_user_name = input("Incorrect username, try again: ")
if re_enter_user_name == "vishesh":
print("Correct user name ur logged in")
return True
return False
input_ = input("enter user name: ")
if input_ == "vishesh":
print("Correct user id, you are logged in: ")
elif input_ != "vishesh":
if not user_name_repeat():
print('Attempts exhausted')
Really, all you need is to return an indicator (a boolean value in this case) from your function to let the caller know, whether the attempts succeeded.
Just use the else in your for loop, else will run after the loop is completed without encountering a break statement. Also, use return in your user_name_repeat() function, since you are calling it in print(user_name_repeat()) So it should return somethinig to the print() to print for:
def user_name_repeat():
for repeat_user_name in range(4):
re_enter_user_name = input("Incorrect username, try again: ")
if re_enter_user_name == "vishesh":
return("Correct user name ur logged in")
break
else:
return "5 attempts completed"
input_ = input("enter user name: ")
if input_ == "vishesh":
print("Correct user id, you are logged in: ")
elif input_ != "vishesh":
print(user_name_repeat())
Since you're working with a function, you should simply return the string instead of printing it inside of the function. That way, you can just return the "incorrect" string after the for loop.
def user_name_repeat():
for repeat_user_name in range(4):
re_enter_user_name = input("Incorrect username, try again: ")
if re_enter_user_name == "vishesh":
return "Correct user name ur logged in"
return "Number of incorrect tries exceeded limit"
Another approach would be using the else clause of the for loop. In loops, the code inside the else clause will only be executed if (and when) the loop ends "naturally"; that is - when the condition running the loop stops being valid (when the for reaches the end of the range(4), for example).
In your code, the loop only ends if the limit of incorrect attempts is reached, since you break the loop if the user inputs the right password. So the following could be done:
def user_name_repeat():
for repeat_user_name in range(4):
re_enter_user_name = input("Incorrect username, try again: ")
if re_enter_user_name == "vishesh":
print("Correct user name ur logged in")
break
else:
print("Number of incorrect tries exceeded limit")
However, I should point out that the first option is way better, specially considering you're printing the return of the function call later (and if the function has no explicit return, you're actually printing None).
You can even take the code out of the function, which should make things easier for you, as Chase's answer points out ;).
Related
Ok, I'm pretty new to python and I was trying to see if I could make a simple login/register system that just uses usernames and passwords. I added this at the start of the code so I didn't have to manually restart it every time I want to test something:
loop = True
while loop == True:
then, I made two lists called 'accountUsernames' and 'accountPasswords' with just a couple of random usernames and passwords. The idea was that every account would have its password and username index be the same, and the code would check if the username and password the user entered while logging in had the same index. When I started writing the code of the register system, I realized I was kind of stuck. I was using the append feature to add the username and password the user had entered into the previously mentioned lists, but when it did so, the code would loop back to the start because it was over, meaning the lists would also be changed to their previous state. I was wondering if there was a way I could define those lists at the start without giving them any values, or changing the values it already has from the previous loop. Here's the full code:
loop = True
while loop == True:
accountUsernames = ['a', '1']
accountPasswords = ['b', '2']
lr = input('Would you like to login or register?\n')
if lr.lower() == 'login':
loginUsername = input('Please enter your username.\n')
loginPassword = input('Please enter your password.\n')
if loginUsername in accountUsernames:
loginIndex = accountUsernames.index(loginUsername)
if accountPasswords[loginIndex] == loginPassword:
print('You have successfully logged in!')
else:
print('Invalid username or password. Please try again.')
else:
print('Invalid username or password. Please try again.')
elif lr.lower() == 'register':
registerUsername = str(input('Please enter a username.\n'))
registerPassword = str(input('Please enter a password.\n'))
registerPasswordConfirmation = str(input('Please confirm your password.\n'))
if registerUsername in accountUsernames:
print('That username is already taken. Please try again.')
elif registerPassword != registerPasswordConfirmation:
print('These passwords do not match. Please try again.')
else:
accountUsernames.append(registerUsername)
accountPasswords.append(registerPassword)
print('You have successfully registered! You can now log in.')
I know it probably has a lot of glaring issues but as I said, I'm pretty new to python. Also, sorry if I over/under-explained the issue. I would really appreciate your help.
I don't really understand the question, but why don't you define the accountUsernames and accountPasswords before the loop starts, like this:
accountUsernames=[]
accountPasswords=[]
while loop:
#insert loop code here
Another suggestion that you should implement is instead of having two lists, to have a dictionary.
userData={}
def addUser(username, password):
global userData
userData[username]=password
def checkUser(username,password):
global userData
if username in userData:
if password==userData[username]:
return True
return False
loop=True
while loop:
#insert code
Just place the accountUsernames and accountPasswords lists outside the loop like this:
accountUsernames = ['a', '1']
accountPasswords = ['b', '2']
loop = True
while loop == True:
lr = input('Would you like to login or register?\n')
if lr.lower() == 'login':
loginUsername = input('Please enter your username.\n')
loginPassword = input('Please enter your password.\n')
if loginUsername in accountUsernames:
loginIndex = accountUsernames.index(loginUsername)
if accountPasswords[loginIndex] == loginPassword:
print('You have successfully logged in!')
else:
print('Invalid username or password. Please try again.')
else:
print('Invalid username or password. Please try again.')
elif lr.lower() == 'register':
registerUsername = str(input('Please enter a username.\n'))
registerPassword = str(input('Please enter a password.\n'))
registerPasswordConfirmation = str(input('Please confirm your password.\n'))
if registerUsername in accountUsernames:
print('That username is already taken. Please try again.')
elif registerPassword != registerPasswordConfirmation:
print('These passwords do not match. Please try again.')
else:
accountUsernames.append(registerUsername)
accountPasswords.append(registerPassword)
print('You have successfully registered! You can now log in.')
Here is my code:
import pickle
current_user = None
class User:
def __init__(self, username, password):
self.username = username
self.password = password
def set_password(self):
self.password = input("Enter NEW password > ")
def __get_password(self):
return self.password
def __get_username(self):
return self.username
def change_password(self):
my_password = input("Enter your CURRENT password > ")
if my_password == self.__get_password():
self.set_password()
else:
print("Please try again")
def display_details(self):
print()
print("Username and password")
print("---------------------")
print("username is: ", User.__get_username(self))
print("password is: ", User.__get_password(self))
print()
def __repr__(self):
return f'username: {self.username}'
try:
users = pickle.load(open("users.pickle", "rb"))
except (OSError, IOError) as f:
users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]
pickle.dump(foo, open("users.pickle", "wb"))
def find_user(name):
for user in users:
if user.username == name:
return user
def add_user():
user = input("Enter NEW user > ")
password = input(f"Enter password for {user} > ")
users.append(User(user, password))
def delete_user():
delete_user = input("Enter the user you wish to remove > ")
user = find_user(delete_user)
if user:
users.remove(user)
print('done')
else:
print(f'user {delete_user} not found')
def display_users():
for user in users:
print(user)
def invalid_entry(): # Response for invalid entries to menu.
print("Invalid entry, please try again")
print()
def menu(): # Display menu, prompt for and accept keyboard choice
print("Please select one of the following:")
print()
print("Enter a if you want to add a new user")
print("Enter d if you want to delete a user")
print("Enter f if you want to find a user")
print("Enter c if you want to change your password")
print("Enter u if you want to display a list of users")
print("Enter q if you want to Quit")
choice = input("")
return choice
while True:
menu_choice = menu()
if menu_choice.lower() == "a":
add_user()
elif menu_choice.lower() == "d":
delete_user()
elif menu_choice.lower() == "f":
current_user = find_user()
elif menu_choice.lower() == "c":
if current_user is None:
print("No user selected!")
continue
else:
current_user.change_password()
elif menu_choice.lower() == 'u':
display_users()
elif menu_choice.lower() == "q":
print("Goodbye")
with open('users.pickle', 'wb') as f:
pickle.dump(users, f)
quit()
else:
invalid_entry()
There's clearly something wrong as it's getting stuck in a loop:
Enter your CURRENT password > password
Enter your CURRENT password > password
Enter your CURRENT password >
I can see PyCharm is coming up 'local variable my_password is not used' too.
I tried removing my_password = input("Enter your CURRENT password > ") from the def change_password() block, but that just results in a fatal error.
I also tried renaming the first change_password function to update_password and updating the second one accordingly, so that it went...
def change_password():
update_password()
...but that didn't work either.
This is the logic that I want to use:
IF the user selects 'c' in the menu THEN do the following...
Prompt the user to enter their current password
IF the entered input matches their current password THEN prompt them to enter a new password and update their password accordingly
IF the entered input does not match their current password THEN prompt them to try again
Any help please? TIA
By the way, I'm puzzled that PyCharm is coming up 'unresolved reference 'foo''. That section seems to work OK, but any insights on why that is and if it's a problem or not would be appreciated.
Edit: I've updated the code in line with the suggestions, as much as I can, anyway.
Edit 2: PyCharm said that self in if my_password == self.__get_password(self) is an unexpected argument, so I removed it, and that didn't seem to do any harm.
You're not stuck in a loop, you stuck in recursion
def change_password():
my_password = input("Enter your CURRENT password > ")
change_password()
notice that you just keep calling change password over and over... also you have double methods for some reason, use the ones in you User class.
when 'c' is chosen you have no context, you don't know WHO is trying to change their password, so first you must ask who the user is, try the following changes:
before your while true loop put current_user = None
change the entry for 'f' to be current_user = find_user()
and the entry for 'c' to be
if current_user is None:
print("No user selected!")
continue
else:
current_user.change_password()
The other change_password function in the outer scope also requests command line input. try to eliminate all the unneeded
input("Enter your CURRENT password > ")
except for one and use parameters in your function calls instead.
On top of that, the outer scope change_password() function is calling itself over and over, because its shadowing the inner one. Try renaming one of the two.
I am doing a basic Python assessment on a password vault but am getting errors that I can't seem to solve myself. and btw guys I didn't come here for a grammar and punctuation lesson, so if you are just here to edit my question and not offer any assistance please dont bother.
For example, in this part of the code I want the user to input 1 or 2, and if he selects 1 it asks him to log in, while if he selects 2 it asks him to register. But at the moment it is completely ignoring the parameters and accepting anything.
Another problem is that when the user enters the valid password, instead of just stopping at password correct, it for some reason re-asks "what is your username."
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()
----------------------------------------------------------#Full code begins now
l_p = ""
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")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break #the break loop exits the current loop and continues with the next programes following it
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")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break
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:
input_username = input("")
if 0 < len(input_username) < 16:
print('''Nice, username''')
break
elif input_username == "":
print("Please enter an answer")
else:
print('''Your username should be a maximum of 15 charecters, ''')
print('''-------------------------------------------------------------------------''')
while True:
input_lockerpassword = input('''Now it's time to setup a password for your locker, It should be between 4
and 10 charecters long,
''')
if len(input_lockerpassword) > 4 and len(input_lockerpassword) < 11:
print('''{}, is locked in thanks for joining Password Locker'''.format(input_lockerpassword))
break
else:
print("It should be between 4 and 10 charecters long!")
print('''
-------------------------------------------------------------------------------------------''')
def login_originup1():
print(''' Welcome to password vault, You can either login or create a New account''')
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()```
Ok, first of all, you should know that the input() function returns a string and, as such, your first condition : if login_orsignup1 != 1 will always be true, because the string object '1' isn't equal to the int object 1. As for why you get asked again for the user after having a good password, that is because the break statement only breaks from the current loop. So you only break of this loop to get back at the start of your username verification loop. I would suggest a cleaner implementation like so :
# login or sign-up loop
while True:
login_orsignup1 = input(" Press \n1) to Log in \n2) to register a new account")
# you can have the input result in a variable like so, if you want to use it later on
if login_orsignup1 == "1": # you said '1' was for login, right?
# or you can test this directly in your if statement
# if it is only needed for this condition
while input("What is your username: ") != username:
print("Incorrect username")
# same thing for password, but could be implemented another way if you
# don't want to loop until the user gets the correct password
while input("What is your password: ") != input_lockerpassword:
print("Incorrect password for this username")
# your code gets here only if the user entered the right credentials
# so you can now break of the login or sign-up loop
break
elif login_orsignup1 == "2":
# code for registration here
This could be good enough for a simple thing. I would recommend designing this console program by following concepts of a state-machine and adding more code at each step to handle cases like going back one step or back at the start.
Hope this helps
the problem is in your login_originup1 function you are making three While loops that the program can't escape from in your function you are asking if login_orsignup1 != 1
without an else statement so if the user wanted to login he would press input in "1" then the program will say that
"1" =! 1 is false
it will look for an else statement But not find one so it will go back to the start of the loop and ask the user to input again. this is it for the First Loop.
Now if the user Inputs in "2" (which means that the user wants to register) it will make him log-in because:
"2" =! 1is true
and will continue to the next while loop in here you will be asking for the username and the user will give the username. Now this is it for the Second Loop
we now go to the last loop where you ask for the Password and the User Will give the Password. The program Will either 1. say that it was false and ask for the password again or 2. it will accept the password and Break the While loop. Now this is it for the Third Loop
so why is it asking me for the Username Because the break statement breaks only the while loop it is in so that break statement broke only the third while loop and was back to the Second Loop which the Second Loop will bring us back into the Third Loop again
so how to fix this?
simple like this:
def login_originup1():
print('Welcome to password vault, You can either login or create a New account')
while True:
login_orsignu = input('Press\n1) to Log in\n2) to register a new account\n')
loopBreaker = 0
if loopBreaker:
break
if int(login_orsignu) != 1:
while True:
if loopBreaker:
break
username = input('What is your,\nUsername:')
if input_username == username:
l_p = input('What is your password ')
while True:
if loopBreaker:
break
if l_p == input_lockerpassword:
print("Password Correct")
loopBreaker = 1
break
Can someone try to help me make with this, please. So once the user guesses 3 times the entire program closes, but once the user gets it wrong it doesn't make them exit the program. Yes I'm aware that I'm asking the same question again but I haven't got my question answered yet so please can someone help.
Here's another one I'm trying out. Any Suggestions on how to do exit the program if the user gets a certain number of attempts by trying to guess the password wrong. I've been trying to use sys.exit and exit()but it hasn't been working for me, so maybe you can try to that , (but remember my teacher wants it so that it on IDLE).
Counter=1
Password=("Test")
Password=input("Enter Password: ")
if Password == "Test":
print("Successful Login")
while Password != "Test":
Password=input("Enter Password: ")
Counter=Counter+1
if Counter == 3:
print("Locked Out: ")
break
counter = 1
password = input("Enter password: ")
while True:
if counter == 3:
print("Locked out")
exit()
elif password == "Test":
print("That is the correct password!")
break
else:
password = input("Wrong password, try again: ")
counter += 1
Move your counter check into the while loop.
Also use getpass for getting password input in python :)
import sys
import getpass
counter = 1
password = getpass.getpass("Enter Password: ")
while password != "Test":
counter = counter + 1
password = getpass.getpass("Incorrect, try again: ")
if counter == 3:
print("Locked Out")
sys.exit(1)
print("Logged on!")
You need to move the condition counter==3 inside the while loop
This can also be done in this way
import sys
password = input("Enter password : ")
for __ in range(2): # loop thrice
if (password=="Test"):
break #user has enterd correct password so break
password = input("Incorrect, try again : ")
else:
print ("Locked out")
sys.exit(1)
#You can put your normal code that is supposed to be
# executed after the correct password is entered
print ("Correct password is entered :)")
#Do whatever you want here
An even better way is to wrap this password-checking thing into a function.
import sys
def checkPassword():
password = input("Enter password : ")
for __ in range(2):
if (password=="Test"):
return True
password = input("Incorrect, try again : ")
else:
print ("Locked out")
return False
if (checkPassword()):
#continue doing you main thing
print ("Correct password entered successfully")
How can I link the second info() call to a text file ?
print("Hi,welcome to the multiple choice quiz")
def info ():
print("Firstly we would like to collect some personal details:-?")
name = input("Please enter your first name?")
surname =input ("please enter your surname?")
email_address = input ("please enter your email addres #.co.uk")
username = input (" Chose a username?")
password = input ("Enter a Password?")
validation()
def validation():
correct = 0
while correct == 0:
correct=input(" is the following data is correct ?")
if correct in ["Y,y"]:
print("Well done you have registered for the quiz")
elif correct in ["N,n"]:
info()
else:
info()
You might want to drop your while loop.
info() calls your validation. "if" the data is correct, you finish, "else" you just call info() again.
That is pretty much what you did already. maybe you wanted it to look more like this:
print("Hi, welcome to the multiple choice quiz")
def info ():
print("Firstly we would like to collect some personal details:-?")
name = input("Please enter your first name?")
surname = input("please enter your surname?")
email_address = input("please enter your email address #.co.uk")
username = input(" Chose a username?")
password = input("Enter a Password?")
validation()
def validation():
correct = 0
correct = input(" is the data is correct ?")
if correct in ["Y,y"]:
print("Well done you have registered for the quiz")
elif correct in ["Y,y"]:
info()
else:
print "please type y or n"
validation()
info()
You wrote:
if correct in ["Y,y"]:
print("Well done you have registered for the quiz")
elif correct in ["N,n"]:
info()
else:
info()
Firstly, correct in ["Y,y"] will not do what you expect. ["Y,y"] is a list containing one element: "Y,y". That means correct in ["Y,y"] if and only if correct == "Y,y", and the user is not likely to enter that! You probably want a list with two elements: ["Y", "y"]. in can also test containment within strings, so you could use "Yy". You don't want a comma in there because then if the user enters just a comma that will pass the test as well, which is silly.
Putting that issue aside, if the user enters y or Y, it prints well done. If they enter n or N, info() is called. If they enter something else, info() is still called. That last part is surely not what you want: entering "N" and entering "A" should have different results! You want the user to be told that it's not valid. That part is easy, print a message. Then you want them to be asked again. Since they'll be asked for every iteration of your while loop, you just have to ensure that the loop continues. The loop will run as long as the condition correct == 0 is true, so just set correct to 0 and that will happen. So something like this:
else:
print("That's not valid")
correct = 0
OK, now to your question. You want to save those personal details to a file. You can't do that properly with the way your program is organised. The variables in info are local, so validation can't access them to save them. info has to do the saving (perhaps indirectly by passing the data along to another function). What we could do is have validation report the result of asking the user and let info decide what to do based on that:
def info ():
# collect data
if validation():
# save data
def validation():
correct = 0
while correct == 0:
correct=input(" is the following data is correct ?")
if correct in ["Y", "y"]:
print("Well done you have registered for the quiz")
return True
elif correct in ["N", "n"]:
return False
else:
print("That's not valid")
correct = 0
return will exit the validation function (thus ending the loop) and give the value returned to info to decide if the data should be saved.
Since the return statements end the loop, the only way the loop can continue is the else is reached, in which case explicitly making it continue with correct = 0 is silly. We can just make the loop go on forever until the function returns:
def validation():
while True:
correct=input(" is the following data is correct ?")
if correct in ["Y", "y"]:
print("Well done you have registered for the quiz")
return True
elif correct in ["N", "n"]:
info()
return False
else:
print("That's not valid")