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

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

Related

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.

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

imbedded if statement not working properly

his is my first time using this website, so i dont know how to use it properly... apologies if its difficult to read.
i have some code to make a login system for my project, and i have used if and else statements to let the user to log in. however, while it works as in there are no error messages its not doing what i would like it to do. when the user login is, it asks them for the username:
username = input("Enter login name: ")
if username in Users:
passw = input("Enter password: ")
if passw in Users:
print ("Login successful!")
however if the username is correct, the program moves onto " passw = input("Enter password: ") " but no matter if the password is correct or not, it goes back to the login menu... im not sure how to fix it.
#full code:
global number
global Users
global username
number = 1
Users = {}
status = ""
def newuser():
global number
print('To create your unique username, please answer these few questions: ')
first = input('Please type your first name: ')
second = input('Please type your surname/last name: ')
year = input('Please type your birth year: ')
part1 = (first[:3])
part2 = (second[:3])
part3 = (year[2:])
username = part1 + part2 + part3
username = str(part1[:3] + part2[:3] + part3[:2] + '' + str(number))
number = number + 1
print('')
print ('here is your unique username: ')
print (username)
print('')
print ('Make sure you know your username for when you login in next time!')
passw = input('please type in your password to login to your account with: ')
Users[username] = passw
print('')
print ('Your account is made! Taking you back to the menu... ')
print('')
def olduser():
global username
global passw
global Users
username = input("Enter login name: ")
if username in Users:
print (Users)
passw = input("Enter password: ")
if passw in Users:
print ("Login successful!")
mainmenu()
else:
print("User doesn't exist!")
def mainmenu():
print('test for main menu is ready')
while status != "q":
status = input("Are you a registered user? y/n? Press q to quit: ")
if status == "n":
newuser()
elif status == "y":
olduser()
else:
print('invalid input try again')

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 3 quest command, IndentationError: unindent does not match any outer indentation level

def register():
print("Register")
login = input("Enter login")
passwd = input("Enter password")
passwdacc = input("Accept password")
if passwdacc = passwd:
print("You have registered, now please sign up")
else:
print("Try again, passwords dont matches")
login2 = input("Enter login")
password = input("Enter password")
if password = passwd and login2 = login
print("Accepted")
else:
print("Try again")
sign_up()
Error(s), warning(s):
File "source_file.py", line 3
login = input("Enter login")
^
IndentationError: unindent does not match any outer indentation level
Apart from wrong indentation, in conditional statements you need to replace assignment operators with comparison operators. Also, a : is missing from an if statement.
def register():
print("Register")
login = input("Enter login")
passwd = input("Enter password")
passwdacc = input("Accept password")
if passwdacc == passwd:
print("You have registered, now please sign up")
else:
print("Try again, passwords don't match")
login2 = input("Enter login")
password = input("Enter password")
if password == passwd and login2 == login:
print("Accepted")
else:
print("Try again")
def register():
print("Register")
login = input("Enter login")
passwd = input("Enter password")
passwdacc = input("Accept password")
if passwdacc = passwd:
print("You have registered, now please sign up")
else:
print("Try again, passwords dont matches")
login2 = input("Enter login")
password = input("Enter password")
if password = passwd and login2 = login
print("Accepted")
else:
print("Try again")

Categories

Resources