Python - Does not exit on the third input - python

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

Related

My script can't recognise names inside the username file

It can see the file, if i change the name on the path slightly run seizes to function but eithr way it can't read the words in the file despite being able to before while I was writing the program. And now suddenly it doesn't work, the file location is the same and all.
P.S. I have no idea how to specify code on overflow
filen = 'C:\Users\fabby\Documents\Extra Things I Might Need\Port Folio Stuff\Python\usernames'
usern = open(filen, 'r')
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
def func():
user = input("Enter new Username: ")
passs = input("Enter new Password: ")
passs1 = input("Confirm password: ")
if passs != passs1:
print("Passwords do not match!")
else:
if len(passs) <= 6:
print("Your password is too short, restart:")
elif user in usern:
print("This username already exists")
else:
usern = open(filen, "a")
usern.write(user+", "+passs+"\n")
print("Success!")
while True:
if userr not in usern:
again = input("This username does not exist, would you like to try again? ")
if again == ("No"):
func()
elif again == ("no"):
func()
elif again == ("Yes"):
print("Try again:")
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
elif again == ("yes"):
print("Try again:")
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
elif userr in usern:
print("Good, you have entered the zone")
I am not sure I have full understand your means, but as your code, I have some suggestions:
close file if you open it
use f.readline() and str.split() to parse username and passwd and store in array, so you can use in to check, if the file is not to large.

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.

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:

python - Password checker program, while loops not working

I am making a password validator/checker program as part of my computing assignment.It must have an uppercase and lowercase letter and be at least 8 characters long.
So far I have done this:
new_password = input("Please enter your new password: ")
new_password2 = input("Please enter your new password again: ")
while new_password != new_password2:
print("The passwords don't match up.")
new_password = input("Please enter your new password: ")
new_password2 = input("Please enter your new password again: ")
if new_password == new_password2:
length = len(new_password)
while int(length) < 8:
print("Your password must be longer")
new_password = input("Please enter your new password: ")
new_password2 = input("Please enter your new password again: ")
letters = set(new_password)
lower = any(letter.islower() for letter in letters)
while new_password == new_password2:
if not lower:
print("Your password must contain a lowercase letter")
new_password = input("Please enter your new password: ")
new_password2 = input("Please enter your new password again: ")
upper = any(letter.isupper() for letter in letters)
while new_password == new_password2 :
if not upper:
print("Your password must contain an uppercase letter")
new_password = input("Please enter your new password: ")
new_password2 = input("Please enter your new password again: ")
The code runs, but for some reason, the while loops do not work as even if the condition is right,( eg. the password contains an uppercase letter), the option for the user to enter the password again is being displayed. Can someone take a look and tell me the problem here? Thanks
You want to only have one while loop in which every requirement is checked. See the following code:
valid_password = False
while not valid_password:
new_password = input("Please enter your new password: ")
new_password2 = input("Please enter your new password again: ")
if new_password != new_password2:
print("The passwords don't match up.")
continue
elif len(new_password) < 8:
print("Your password must be longer")
continue
elif new_password.upper() == new_password or new_password.lower() == new_password:
print("Your password must contain at least one lowercase and uppercase letter")
continue
else:
print("Password Accepted!")
valid_password = True
Hope this helps!
a= int (input("Enter Passcode: "))
if a == 1974:
print (" Welcome!! ")
else:
print ("Wrong Passcode")
print ("Run again")

Why does this programme not stop after three password guesses?

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.

Categories

Resources