Log in is always saying it is incorrect [duplicate] - python

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.

Related

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

How do I stop my code from infinitely printing "Access Denied"?

name = input(str("Enter your firstname "))
surname = input(str("Enter your surname "))
username = surname[0:2] + name[0:3]
password = input("Make a password ")
passwordconfirm = input("Enter password again ")
while password != passwordconfirm:
print("Password is not the same try again ")
password = input("Make a password ")
passwordconfirm = input("Enter password again ")
print("This is your username and password:\n" + username + "\n" + password)
attempt = 0
login1 = input("Enter your username ")
login2 = input("Enter your password ")
while True:
if login1 == username and login2 == password:
print("Welcome back " + name + " " + surname)
break
else:
print("Access denied")
attempt += 1
#When I run the program and username or password is incorrect it starts to infinitely print "Access Denied"
breakĀ breaks out of a loop, not anĀ ifstatement or function as others have mentioned above. Your program will stop running itself if conditions are matched.
if login1 == username and login2 == password:
print("Welcome back " + name + " " + surname)
else:
print("Access Denied.")
Alright, I think the code needs a few more steps to make it work. If I understand it well, you want the user to sign up for a new account using username and password. Then, you need to verify it to see if it's correct.
Here is a sample:
#*********** BEGIN ACCOUNT CREATION ***************
msg = "Invalid entry. Try again."
print("Welcome to Python Account!")
while True:
# ***** THIS BLOCK CREATES NEW USERNAME
try:
username = input("Create New Username: ") #create new username
except ValueError:
msg
else:
try:
username2 = input("Confirm username: ") # confirm username
except ValueError:
msg
else:
if username2 != username: # if no match, try again
print("Usernames do not match. Try again.")
continue
else:
print("Username created!")
#THIS BLOCK CREATES NEW PASSWORD
while True:
try:
password = input("Create a new password: ")
except ValueError:
msg
else:
password2 = input("Confirm password: ")
if password2 != password:
print("Passwords don't match. Try again.")
continue
else:
print("Password created!")
break
break
break
# ****************** END ACCOUNT CREATION ******************
# # ****************** BEGIN ACCOUNT LOGIN *****************
print("PLEASE LOG INTO YOUR ACCOUNT")
attempts = 5 # this will allow 5 attempts
while attempts > 0:
attempts -= 1
try:
usrnm = input("Enter username: ")
pwd = input("Enter password: ")
except ValueError:
msg
else:
if usrnm.isspace() or pwd.isspace():
print("Space not allowed.")
continue
elif usrnm == '' or pwd == '':
print("Value needed.")
continue
elif usrnm != username2 or pwd != password2:
print("Credentials do not match. Try again.")
print(f'You have {attempts} attempts left')
if attempts == 0: # once user exhausts attempts, account is locked
print("You have been locked out of your account")
break
continue
else:
print(f"Welcome {username2}!")
break
break
# *************** END ACCOUNT CREATION *************
WITHOUT TRY/EXCEPT
#*********** BEGIN ACCOUNT CREATION ***************
msg = "Invalid entry. Try again."
print("Welcome to Python Account!")
while True:
# ***** THIS BLOCK CREATES NEW USERNAME
username = input("Create New Username: ") #create new username
username2 = input("Confirm username: ") # confirm username
if username2 != username: # if no match, try again
print("Usernames do not match. Try again.")
continue
else:
print("Username created!")
#THIS BLOCK CREATES NEW PASSWORD
while True:
password = input("Create a new password: ")
password2 = input("Confirm password: ")
if password2 != password:
print("Passwords don't match. Try again.")
continue
else:
print("Password created!")
break
break
# ****************** END ACCOUNT CREATION ******************
# # ****************** BEGIN ACCOUNT LOGIN *****************
print("PLEASE LOG INTO YOUR ACCOUNT")
attempts = 5 # this will allow 5 attempts
while attempts > 0:
attempts -= 1
usrnm = input("Enter username: ")
pwd = input("Enter password: ")
if usrnm.isspace() or pwd.isspace():
print("Space not allowed.")
continue
elif usrnm == '' or pwd == '':
print("Value needed.")
continue
elif usrnm != username2 or pwd != password2:
print("Credentials do not match. Try again.")
print(f'You have {attempts} attempts left')
if attempts == 0: # once user exhausts attempts, account is locked
print("You have been locked out of your account")
break
continue
else:
print(f"Welcome {username2}!")
break
# *************** END ACCOUNT CREATION *************

python while with if/else statement

It's for my school work. I need to fix this code. Can someone maybe help me? I would really appreciate that. I can't manage to fix the "else" part. :)
CorrectUsername = "Username"
CorrectPassword = "Password"
loop = 'true'
while (loop == 'true'):
username = raw_input("Please enter your username: ")
if (username == CorrectUsername):
password = raw_input("Please enter your password: ")
if (password == CorrectPassword):
print "Logged in successfully as " + username
loop = 'false'
else:
print "Password incorrect!"
else:
print "Username incorrect!"
This is what I've done so far
CorrectUsername = "Username"
CorrectPassword = "Password"
loop = "true"
while (loop == 'true'):
username = input("Please enter your username: ")
if (username == CorrectUsername):
password = input("Please enter your password: ")
if (password == CorrectPassword):
print("Logged successfully as " + str(username))
loop = "false"
else:
print("Password incorrect!")
else:
print("Username incorrect")
You have to indent the else properly it's matching if. Also use boolean values True/False, better than strings
CorrectUsername = "Username"
CorrectPassword = "Password"
loop = True
while loop:
username = input("Please enter your username: ")
if username == CorrectUsername:
password = input("Please enter your password: ")
if password == CorrectPassword:
print("Logged successfully as " + str(username))
loop = False
else:
print("Password incorrect!")
else:
print("Username incorrect")

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.

Account creation program is not reading file properly

I've been making a program that allows the user to create an account which saves to a txt file, and allows them to login. The text now saves to the file (which I was unable to make work earlier due to using w+ instead of a+) but I am not quite sure I understand how split() works. When I try to use the info saved to the txt file the program returns that the username cannot be found. If anyone could fix this code id appreciate it.
I began a few weeks ago so a lot of this is new to me.
AccountsFile = open("AccountProj.txt", "a+")
AccountList = [line.split('\n') for line in AccountsFile.readlines()]
#Creates an account
def createaccount():
while True:
newname = (input("Please create a username: "))
if newname in AccountsFile:
print("Username already in use.")
continue
elif newname not in AccountsFile:
newpassword = input("Please create a password: ")
checkpassword = input("Re-enter password: ")
if checkpassword == newpassword:
print("Account Sucessesfuly created!")
AccountsFile.write(newname + '\n')
AccountsFile.write(checkpassword + '\n')
AccountsFile.close()
break
elif checkpassword != newpassword:
print("Passwords do not match")
continue
#Logs into an account
def loginaccount():
while True:
username_entry = input("Enter username: ")
if username_entry not in AccountList:
print("Username not found. Please enter a valid name")
continue
if username_entry in AccountList:
password_entry = input("Enter password: ")
if password_entry in AccountList[AccountList.index(username_entry) + 1]:
print("Login sucessful!")
AccountsFile.close()
break
if password_entry not in AccountList[AccountList.index(username_entry) + 1]:
print("Username and password do not match. Please try again.")
AccountsFile.close()
continue
while True:
#Asks if user wants to create or login to an account
loginchoice = input("Would you like to login? (Y/N) ")
if loginchoice in ('Y', 'N'):
if loginchoice == 'Y':
loginaccount()
if loginchoice == 'N':
createchoice = str(input("Would you like to create an account? (Y/N) "))
if createchoice in ('Y', 'N'):
if createchoice == 'Y':
createaccount()
if createchoice == 'N':
pass
break
else:
print("Invalid Input")
def CreateAccount():
Username = input("Username: ") #Enter Username
Username.replace(" ", "") #Removes spaces (Optional)
AppValid = True #Default value that changes if duplicate account found
File = open("Accounts.txt","r") #Checking if username already exits
for Line in File:
Account = Line.split(",")
if Account[0] == Application:
print("There is already an Account with this Username")
AppValid = False #Changing value if username exits
File.close()
if AppValid == True: #If username not found, carries on
Password = input("Password: ") #Asks for Password
CheckPassword = input("Password: ")
if Password == CheckPassword:
print("Password's Match!") #Password Match
else:
print("No match")
File = open("Accounts.txt","a") #Writing new account to File
File.write(Username + "," + Password + "\n")
File.close()
def ViewAccount(Username, Password):
File = open("Accounts.txt","r")
Data = File.readlines()
File.close()
if len(Data) == 0:
print("You have no Accounts") #Account not found since no accounts
else:
AccountFound = false
for X in Data: #Looping through account data
if X[0] == Username: #Username match
if X[1] == Password:
AccountFound = true
print("Account Found")
if AccountFound = false:
print("Account not FOUND")
Theres some code i threw together (JK my hand hurts from typing that and my keyboard is screaming) but back to the point .split(" ") would split a string into a list based on spaces for that example, eg:
String = "Hello There"
String = String.split(" ") #Or String.split() only owrks for spaces by default
print("Output:", String[0]) #Output: Hello
print("Output:", String[1]) #Output: There
String = "Word1, Word2"
String = String.split(", ") #Splits string by inserted value
print("Output:", String[0]) #Output: Word1
print("Output:", String[1]) #Output: Word2
String = "abcdefghijklmnop"
String = String.split("jk") #Splits string by inserted value
print("Output:", String[0]) #Output: abcdefghi
print("Output:", String[1]) #Output: lmnop
Check AccountList - both split() and readlines() create a list for you, so you have a list of lists and your username_entry check can't work that way.

Categories

Resources