In the following code, I am trying to use a flag to break out of the loop when true (password is correct) but limit the number of incorrect tries to 3.
def secretagent():
flag=False
while flag==False:
for i in range(3):
password=input("Enter password:")
if password=="secret007":
print("Access Granted!")
flag=True
break
else:
print("Impostor...access denied!")
print("Welcome Secret agent...let's get started...")
#print("You have tried 3 times and failed. Goodbye forever!")
secretagent()
Here, for ease, is the trinket: https://trinket.io/python/8869529c45
Can anyone suggest a suitable solution – the most pythonic way and for learning purposes explain the best way to approach this. e.g. should the for loop or while loop be on the outside and why?
Currently, it still allows unlimited number of tries so my for loop has obviously been placed wrong.
>Solution :
Use int instead of bool
import sys
number_of_tries = 0
while True:
if number_of_tries == 3:
sys.exit() # exit the program
password=input("Enter password:")
if password=="secret007":
print("Access Granted!")
break
else:
print("Impostor...access denied!")
number_of_tries += 1
print("Welcome Secret agent...let's get started...")
Or even simpler with for loop:
for _ in range(3):
password=input("Enter password:")
if password=="secret007":
print("Access Granted!")
break
else:
print("Impostor...access denied!")
else: # it means no break was called
sys.exit()