While loop to maximise password attempts – Python 3

I’m practising my coding – pretty new to this – and i’m trying to create a login system, all is working well so far but i’m trying to use a while loop to maximise the number of user attempts at inputting the correct password. Even if the user inputs the correct password, the loop will carry on until the loop is completed and will continue to say carry on.

login = {
    "alex": "dog123"
}
passkey = login.values()
correct_user = True


while correct_user:
    user = input("Please input your username ")
    if user in login:
        print(f'Hello {user}, please input your password.')
        correct_user = False
    else:
        print("Invalid user")

attempt = 0
max_attempts = 3
correct_password = True

while correct_password:
    password = input(">")
    if password in passkey:
        print(f"""Welcome back {user}! 
How can i help you today?""")
        correct_password = False
    else:   
        while attempt < max_attempts:
            print("try again")
            attempt += 1
            password = input(">")
            if password in passkey:
                correct_password = False
        else:
            print("too many guesses!")
            break

>Solution :

You can shorten that to:

attempt = 0
max_attempts = 3
passkey = ['sesame']

while attempt < max_attempts:
    password = input(">")
    if password in passkey:
        print(f"""Welcome back {user}! How can i help you today?""")
        break
    else:
        attempt += 1
        if attempt <3:
            print("try again")    
else:
    print("too many guesses!")

Leave a Reply