Why does this programme not stop after three password guesses? - python

username = "Patrick"
password = "Kearney"
username = input("Username:")
while username != "Patrick":
print("Please try again.")
username = input("Enter your username again.")
password = input("Password:")
incorrect = 0
threshold = 3
while password != "Kearney":
print("Please try again.")
password = input("Enter your password again.")
if password != "Kearney":
incorrect += 1
else:
print("Welcome Patrick")
incorrect = 0
if incorrect == threshold:
import sys
sys.exit()

For your if to be executed inside the while loop, you should indent it properly, this should work:
username = "Patrick"
password = "Kearney"
username = input("Username:")
while username != "Patrick":
print("Please try again.")
username = input("Enter your username again.")
password = input("Password:")
incorrect = 0
threshold = 3
while password != "Kearney":
print("Please try again.")
password = input("Enter your password again.")
if password != "Kearney":
incorrect += 1
else:
print("Welcome Patrick")
incorrect = 0
if incorrect == threshold:
import sys
sys.exit()
EDIT: as #Benjamin pointed out in the comments this is going to allow for 4 trials (1 outside the while loop and 3 inside the loop), set threshold to 3 or incorrect to 1 at the beginning to fix this.

Related

im trying to make a age and name approval. When they have 0 chances they cant continue. My problem is when they get 0 they can still continue

password = "12345"
for i in range(4):
pwd = input("ENTER YOUR PASSWORD : ")
j = 3
if(pwd == password):
print("WELCOME!")
break
else:
print("Not Valid, try again and chances left are",j-i)
continue
If you want to continue even if it reaches 0 chance. Instead of using for loop use while loop instead. So until the requirements meet, it's don't stop.
password = "12345"
while True:
pwd = input("ENTER YOUR PASSWORD : ")
j = 3
if(pwd == password):
print("WELCOME!")
break
else:
print("Not Valid, try again")
continue
with nested if to restart every time it reach zero
password = "12345"
chances = 4
while True:
pwd = input("ENTER YOUR PASSWORD : ")
j = 3
if(pwd == password):
print("WELCOME!")
break
else:
print("Not Valid, try again")
chances -= 1
if(chances <= -1):
print("Your chance depleted pls restart again")
#restart chance
chances += 4
continue
output

Python - Does not exit on the third input

This is basic python. I want the user to enter the displayed username and password 3 times. When I entered an incorrect input in the first and second tries, the code in elif functions correctly but when I incorrectly entered it in the third try, it doesn't run the statement in the elif. Can you explain why this is happening?
The code is supposed to exit when entered the wrong input. I also want to make the user enter the correct input for 3 times then it will print the welcome.
username = "Username"
password = "Password"
tries = 0
print("Your username: Username")
print("Your password: Password")
print(" ")
enterusername = str(input("Enter your username:"))
enterpassword = str(input("Enter your password:"))
while tries < 2:
if (password == enterpassword and username == enterusername):
enterusername = str(input("Enter again your Username:"))
enterpassword = str(input("Enter again your password:"))
tries = tries + 1
else:
exit("Password or username is incorrect.")
print("Welcome")
It's because you set
while tries < 2:
on the third try, tries=2, so your while loop doesn't run. Change it to while tries < 3
Your logic goes as follows:
Ask for input.
In loop:
Validate last input.
Ask new input.
You can see from this that the input form the last iteration will not be validated. You need to either:
Validate the first input before the loop and change the loop's order.
Validate the last input after the loop.
1
enterusername = input("Enter your username:")
enterpassword = input("Enter your password:")
if (password == enterpassword and username == enterusername):
while tries < 2:
enterusername = input("Enter again your Username:")
enterpassword = input("Enter again your password:")
if password == enterpassword and username == enterusername:
tries += 1
else:
exit("Password or username is incorrect.")
else:
exit("Password or username is incorrect.")
2
enterusername = input("Enter your username:")
enterpassword = input("Enter your password:")
while tries < 2:
if password == enterpassword and username == enterusername:
enterusername = input("Enter again your Username:")
enterpassword = input("Enter again your password:")
tries += 1
else:
exit("Password or username is incorrect.")
if password == enterpassword and username == enterusername:
print("Welcome")
else:
exit("Password or username is incorrect.")
I made a few small changes in your code:
input always returns a string so there is no need to convert with str().
x = x + 1 is equivalent to x += 1.
Your condition were complementary so there is no need to write the opposite in an elif - just use else.
To avoid the repeated conditions, reverse the logic: check the input in the while condition and count the tries inside the loop:
enterusername = input("Enter your username:")
enterpassword = input("Enter your password:")
while password == enterpassword and username == enterusername:
if tries == 2:
print("Welcome")
break
enterusername = input("Enter again your Username:")
enterpassword = input("Enter again your password:")
tries += 1
else:
exit("Password or username is incorrect.")
This uses the while/else construct - the else will only be executed if the loop terminated without reaching a break.
You should put
while(tries <= 2):
...
or
while(tries <3):
...

Log in is always saying it is incorrect [duplicate]

This question already has an answer here:
Searching array reports "not found" even though it's found
(1 answer)
Closed 1 year ago.
My code is always saying it is incrorrect even tough it is present on the text file,
it was working before but now isn't for some reason.
def select_login_signup():
while True:
selection = input("Welcome to sports.com, please select"
" \"L\" to Log In with your account or \"S\" to create an account: ")
if selection.lower() == 's':
register()
answer = input("Would you like to Log In? Y/N? ")
while not answer:
if answer.lower() == "y":
login()
break
elif answer.lower() == "n":
exit()
else:
answer = False
print("Invalid answer.")
continue
elif selection.lower() == 'l':
login()
break
else:
print("Invalid answer.")
continue
def register():
username = input("Create your username (no more than 10 characters or less than 4.): ")
while 10 < len(username) < 4:
print('username cannot have more than 10 characters or less than 4.')
username = input("Create your username (no more than 10 characters or less than 4.):
")
break
while username.isnumeric():
print("username must contain at least one letter")
username = input("Create your username (no more than 10 characters or less than 4.):
")
break
password = input("Create a password with letters and numbers: ")
while len(password) < 6:
print("Your password must contain more than 6 characters.")
password = input("Create a password with letters and numbers: ")
continue
while password.isnumeric() or password.isalpha():
print("Your password must contain both letters and numbers")
password = input("Create a password with letters and numbers: ")
continue
login_credentials = open('C:\\Users\\hmarq\\Documents\\UsernameAndPassword.txt', "a")
login_credentials.write(f'\n{username},{password}')
login_credentials.close()
print("Account created successfully.")
def login() -> object:
username = input("Please enter your username: ")
username = username.strip()
password = input("Please enter your password: ")
password = password.strip()
login_credentials = open('C:\\Users\\hmarq\\Documents\\UsernameAndPassword.txt', "r")
login_credentials.readlines()
with open('C:\\Users\\hmarq\\Documents\\UsernameAndPassword.txt', 'r') as
login_credentials:
for line in login_credentials:
login_info = line.split(",")
if username == login_info[0] and password == login_info[1]:
print("Authorized")
authenticated = True
return authenticated
else:
print("Incorrect credentials.")
username = input("Please enter your username: ")
username = username.strip()
password = input("Please enter your password: ")
password = password.strip()
continue
def main():
select_login_signup()
if __name__ == "__main__":
main()
with open('C:\Users\hmarq\Documents\UsernameAndPassword.txt', 'r') as login_credentials
when you open a file, you have to format the data and therefore the data is not the same.
if username == login_info[0] and password == login_info[1]:
I hope it serves you, greetings.

Why is my register and login system looping in python?

This is my login and register system for a game I am programming. However when I try to login using the username and password stored on the text file, it keeps printing "Incorrect credentials" and looping me back to "Please enter your username player 1" and repeating this process. Any feedback on improving and fixing the code would be greatly appreciated. (I am using python 3.6.0)
abc = input("Enter 'n' if a player needs to make a new account, otherwise enter anything to login")
new_users = False
if abc == "n":
while new_users == False:
username = input("Please input a username ")
password = input("Please input a password ")
file = open("users.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
repeat = input("Enter 'n' to make another account, or type anything else to continue")
if repeat == "n":
new_users = False
else:
new_users = True
logged_in1 = False
logged_in2 = False
while logged_in1 == False:
username = input("Please enter your username player 1")
password = input("Please enter your password player 1")
for line in open("users.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
logged_in1 = True
else:
print("Incorrect credentials.")
break
logged_in1 = False
while logged_in2 == False:
username = input("Please enter your username player 2")
password = input("Please enter your password player 2")
for line in open("users.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
logged_in2 = True
else:
print("Incorrect credentials.")
break
logged_in2 = False
this is what the text file currently looks like
Your break statement is in the wrong place. You need to break out of the for loop as soon as you have found that the credentials are correct. Here's a proposed change:
logged_in1 = False
logged_in2 = False
while logged_in1 == False:
username = input("Please enter your username player 1")
password = input("Please enter your password player 1")
for line in open("users.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
logged_in1 = True
break
if not logged_in1:
print("Incorrect credentials.")
while logged_in2 == False:
username = input("Please enter your username player 2")
password = input("Please enter your password player 2")
for line in open("users.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
logged_in2 = True
break
if not logged_in2:
print("Incorrect credentials.")
Also, determining that the credentials are incorrect can only happen after the loop is over.

Checking to see if username already exists

Starting at "#If user does not have account:" the code is printing the output multiple times. I just want it to print the output (either the username is taken or they can continue) once. Then, I want the password to be typed twice and compared to make sure that they match. Can you help me fix this issue?
import colorama
colorama.init()
print_in_green = "\x1b[32m"
print_in_red = "\x1b[31m"
print_in_blue = "\x1b[36m"
print_in_pink = "\x1b[35m"
print_default = "\x1b[0m"
#STAGE 1: Opening the files and grabbing data
users_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
passwords_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
scoreslist_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"
def get_file_contents(file_path):
return [line.strip() for line in open(file_path)]
scoreslist = get_file_contents(scoreslist_path)
def add_file_contents(file_path, contents):
with open(file_path, "a") as file:
file.write(contents)
def login_user(new_account=False):
usernameslist = get_file_contents(users_path)
passwordslist = get_file_contents(passwords_path)
if new_account:
response = 'y'
else:
response = input("-"*50 + "\nWelcome! Do you have an account (y/n)? ")
print("-"*50)
#If user has an account:
if response == "y":
goodlogin = False
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for id in range(len(usernameslist)):
if username == usernameslist[id] and password == passwordslist[id]:
goodlogin = True
if goodlogin:
print(print_in_green + "Access granted!" + print_default)
#Ask if user would like to view leaderboard
leaderboard = input("Would you like to view the leaderboard (y/n)? ")
#If thet want to see scores:
if leaderboard == "y":
print("-"*50 + "\n" + print_in_blue + "Here is the leaderboard!\n" + print_default + "-"*50)
for c in range(0, len(scoreslist)-1):
max = scoreslist[c]
index_of_max = c
for i in range (c+1, len(scoreslist)):
if (scoreslist[i] > max):
max = scoreslist[i]
index_of_max = i
aux = scoreslist[c]
scoreslist[c] = max
scoreslist[index_of_max] = aux
#print(scoreslist)
print(*scoreslist, sep = "\n")
print("-"*50)
#If they don't want to see scores:
else:
print("OK. Thanks for loging in!")
else:
print(print_in_red + "Incorrect Login credentials, please try again by restarting." + print_default)
#If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
print("Ok, please continue!")
else:
print("This username is already taken. Please try another.")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print("Your passwords do not match. Please try again.")
login_user()
The problem with your code lies in the fact that you are printing the message "Ok, please continue!" within your for loop.
...
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
print("Ok, please continue!")
else:
print("This username is already taken. Please try another.")
...
What happens is that every time your usernameslist[id] is checked against the 'newusername' variable, the print statement 'print("Ok, please continue!")' is run, causing the message to be displayed multiple times.
What you can do to fix this issue is to move the print statement out of the for loop, so that, assuming that a new username does not match any username in the usernameslist, the message "Ok, please continue!" will be displayed once to the user before they are prompted to input their password twice.
Here's what should work for you:
...
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
else:
print("This username is already taken. Please try another.")
if goodlogin2 = True:
print("Ok, please continue!")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
...
It looks like you're iterating over your whole list of usernames and printing out a success or error message with each iteration.
Try this instead:
# If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
if newusername in usernameslist:
print("This username is already taken. Please try another.")
else:
goodlogin2 = True
print("Ok, please continue!")
# for id in range(len(usernameslist)):
# if newusername != usernameslist[id]:
# goodlogin2 = True
# print("Ok, please continue!")
# else:
# print("This username is already taken. Please try another.")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print("Your passwords do not match. Please try again.")
This produces the following output for a user with no previous account who enters a name which has not been used:
--------------------------------------------------
Welcome! Do you have an account (y/n)? n
--------------------------------------------------
What is your new username? not_taken2
Ok, please continue!
What is your new password? pwd2
Please enter your new password again.pwd2
Please follow the instructions to log in with your new credentials.
Please enter your username:

Categories

Resources