Home > Software design >  Trouble looping back to certain point and quitting program on 3 wrong guesses
Trouble looping back to certain point and quitting program on 3 wrong guesses

Time:06-05

while True:
  print('enter username: ')
  username = input()

  if username.lower() != 'joe':
    print("imposter!")
    continue
  print(f'Hello {username.capitalize()}')
  
  print('enter password: ')
  password = input()
  tries = 0

  if password != 'Water':
    tries  = 1
    continue    

  if tries == 3:
    print("3 strikes, you're out")
    quit()

  else:
    break

print("access granted")

Trying to make a username and password prompt. I am trying to give infinite tries to username entries, and only 3 chances for a correct password. When you type in the correct user name and password everything works fine. BUT when typing in the incorrect password, it loops back up to enter username, and the 'tries' counter does not work. python noob trying to learn using Automate The Boring Things in Python

CodePudding user response:

You could try restructuring your code like the below:

import sys

access = False
while not access:
    username = input('Enter username: ')
    if username.lower() != 'joe':
        print("imposter!")
        continue
    
    else:
        print(f'Hello {username.capitalize()}')
        for i in range(3):
            password = input('Enter password: ')
            if password == 'Water':
                access = True
                break
        else:
            print("3 strikes, you're out")
            sys.exit()

print("Access granted")

CodePudding user response:

You reset tries = 0 within the loop.

  • Related