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

Python, adding a for loop to limit no. of tries – error in code

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?

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

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()
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