Trying to create program that exits after 6 incorrect attempts at entering username and password

Viewed 46

In the beginning stages of learning Python and I've hit a bit of a snag

I'm trying to create a program that asks for a specific username and password. After 6 incorrect attempts, it will quit the program. Sample code works fine when I put in the correct info. The issue I'm having is when the username is correct but the password is not. I want it to print that the "password doesn't match" and re-ask for the password. It takes me back to the beginning of the program and asks for my username again. Any ideas to solve this? Thank you in advance!

Code can also be found here: https://pastebin.com/4wSgB0we

import sys
incorrect = 0
max_tries = 6

choices = ['Drake', 'swordfish']

run = True

while run:
    while incorrect < max_tries:
       user_input = input('Please enter username: ')
       if user_input not in choices:
          incorrect += 1
          print(f"{user_input} is incorrect. Please try again.")
       else:
          print(f"Welcome back {user_input}.")
          pass_input = input('Please enter password: ')
    
          if pass_input not in choices:
             incorrect += 1
             print("Password does not match. Please try again")
          else:
             run = False
             print('Access granted')
             sys.exit()
            
 if incorrect == max_tries:
    sys.exit()        
1 Answers

If it didn't help you solve the problem.
I will modify.

When your user is correct, you should leave While.
If you do not leave While, the user account will be asked again.

while run:
    while incorrect < max_tries:
        user_input = input('Please enter username: ')
        if user_input not in choices:
            incorrect += 1
            print(f"{user_input} is incorrect. Please try again.")
        else:
            print(f"Welcome back {user_input}.")
            break
    while incorrect < max_tries:
        pass_input = input('Please enter password: ')
        if pass_input not in choices:
            incorrect += 1
            print("Password does not match. Please try again")
        else:
            run = False
            print('Access granted')
            sys.exit()

    if incorrect == max_tries:
        sys.exit()
Related