python while with if/else statement - python

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

Related

How do i make a password and username in trinket python?

i have tried
def main():
while True:
UserName = input ("Enter Username: ")
PassWord = input ("Enter Password: ")
if UserName == Bob and PassWord == rainbow123:
time.sleep(1)
print ("Login successful!")
logged()
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to ----")
main()
but i dont know why it wont work
somebody plz help
The issue is that you haven't defined the username and password as a string in the 'if' statement.
import time
def main():
while True:
UserName = input("Enter Username: ")
PassWord = input("Enter Password: ")
if UserName == "Bob" and PassWord == "rainbow123":
time.sleep(1)
print("Login successful!")
logged()
else:
print("Password did not match!")
def logged():
time.sleep(1)
print("Welcome to ----")
main()

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 *************

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.

If statement in Python always return true

I am trying to write a program which will ask my name and password before giving me access. Somehow I am not writing it right
print("Enter your name:")
myName = input ()
if myName == "Akib":
print("Enter your password")
password = input()
password = "toma"
if password == "toma":
print("Access granted")
else:
print("Not granted")
The issue is you set password to the input and then rest password by setting it to toma so you need to remove password = "toma".
print("Enter your name:")
myName = input ()
if myName == "Akib":
print("Enter your password")
password = input()
if password == "toma":
print("Access granted")
else:
print("Not granted")
password = "password" # store your password here
name = "name" # store your name here
input_name = str(input("> enter your name: "))
input_password = str(input("> enter your password: "))
if input_name == name and input_password == password:
print("access granted !")
else:
print("declined !")
It can be done like-so. Hope this helps :)
You could achieve your desired function like so!
In this case, if the name entered is not 'Akib', it would not even prompt the user to enter the password.
# prompt for name
myName = input("Enter your name: ")
# check if name is correct
if myName == "Akib":
# prompt for password
password = input("Enter your password: ")
# check if password is correct
if password == "toma":
print("Access granted")
else:
print("Not granted")
else:
print("Not granted")

Categories

Resources