Instead of giving the user 3 chances it just prints access denied 3 times but I am not sure how to change the code so that it would give the user 3 chances and also it prints welcome even if the user enters the incorrect details so I would be grateful if someone could help me with this
Tbh i am a very novice programmer so I was not expecting it to work but if it did work i would have expected it to give the user 3 chances and if they get all the chances wrong then it would print something along the lines of “Account locked out”
username = "Student1"
password = "WatfordLenMein"
input1 = input("Enter username: ")
input2 = input("Enter password: ")
for i in range(3):
if username == input1 and password == input2:
break
else:
print("Access denied")
print("Welcome")
1
Your code should rather look like this:
username = "Student1"
password = "WatfordLenMein"
is_login_successful = False
for i in range(3):
# ask the user to enter login/password on every iteration of the loop.
# if you keep this outside, then the user will be prompted to enter
# credentials only once .. which is not what you want.
input1 = input("Enter username: ")
input2 = input("Enter password: ")
# if the login/password match, then the loop is over
if username == input1 and password == input2:
is_login_successful = True
break
else:
print("Access denied")
# as suggested by kuro, the use of a flag simplifies the overall logic
if (not is_login_successful):
print("Account locked out")
exit(1)
print("Welcome")
...
As “kuro” mentioned you have to put the input() function inside the for-loop to check three times if the input is correct:
username = "Student1"
password = "WatfordLenMein"
for i in range(3):
input1 = input("Enter username: ")
input2 = input("Enter password: ")
if username == input1 and password == input2:
print("Welcome")
break
else:
print("Access denied")
You need the inputs to be inside the for loop. This is also a good use-case for the for/else construct.
username = "Student1"
password = "WatfordLenMein"
for _ in range(3):
u = input("Enter username: ")
p = input("Enter password: ")
if u == username and p == password:
print("Welcome")
break
else:
# This will be executed if the for loop terminates due to range exhaustion - i.e., no break
print("Access denied")
The only problem with this is that once you’re outside the loop you don’t know if you got there with a valid username/password or you had too many retries but that’s outside of the scope of your question