Home > database >  Python, adding a for loop to limit no. of tries - error in code
Python, adding a for loop to limit no. of tries - error in code

Time:11-18

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.

CodePudding user response:

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

CodePudding user response:

Personnaly, instead of using a flag, I would only use a for loop and iterate over it 3 times and checking the value of the answer. I would then return True or False, or continue the loop depending on the answer. Then I would print the response based on the return value of the function. Something like that

def secretagent():
  for i in range(3):
    password=input("Enter password:")
    if password=="secret007":
      print("Access Granted!")
      return True
    elif i < 2:
      print("Wrong password, try again")
    else:
      print("Impostor...access denied!")
      return False
      
      
flag = secretagent()

if flag==True:
  print("Welcome Secret agent...let's get started...")
else:
  print("You have tried 3 times and failed. Goodbye forever!")

Your while loop is not necessary since you already know you only want to provide 3 tries to your agent.

Hope this helps.

  • Related