Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading