Block login if too many login attempts

I want to "block login" or end code if user has too many attempts at entering a username or password but can try again by re-running the code

import time 
usernames = ("test","test01", "test02")
passwords = ("test", "test01", "test02")
while True:
    print("Username: ")
    username = input("")
    if username in usernames:
        print("Username Accepted")
    else:
        print("Try Again (10 sec)")
        time.sleep(10)
        continue
    break
while True:
    print("Password: ")
    password = input("")
    if password in passwords:
        print("Password Accepted")
    else:
        print("Try Again (10 sec)")
        time.sleep(10)
        continue
    break
print("Access Granted")

>Solution :

I don’t know what you mean with "block login" or "end code" but here is one way to signal to calling code if the correct password was locked, or if it should be locked:

import time 

usernames = ("test", "test01", "test02")
passwords = ("test", "test01", "test02")


def username():
    print("Username: ")
    username = input("")
    if username in usernames:
        print("Username Accepted")
    else:
        print("Try Again (10 sec)")
        time.sleep(10)
        continue
    break

def password(n):
    while True:
        print("Password: ")
        password = input("")
        if password in passwords:
            print("Password Accepted")
            return True
         n -= 1
         if n == 0:
            return False
         print("Try Again (10 sec)")
         time.sleep(10)  

username()
if not password(3):
    print("Locked")
else:
    print("Access Granted")

It’s best practice, btw, to not reveal if the username is correct. In other words, you read (username, password) then you validate it and tell the user if the combination is correct. Also, I would sleep 0 the first failure, but then make it exponentially worse each on each failure:

Leave a Reply