Python Forum

Full Version: How do i add limits to this code ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
while True:
  answer1 = input("Password: ")
  if answer1 != "123":
    print("Wrong Password")
    continue
  else:
    print("Welcome!")
    break
Hi , i would like to ask , if i would like to add a limit to how many times a user can input password, how
should i do it ?

Many thanks in advance
set a counter before entering loop
within loop:
increment counter on each iteration
break (with message) after limit reached.
The easiest way I know is to add a count to each time through the loop:
attempts = 0

while True:
    attempts += 1
    if attempts < 5:
        
       #check password 
           
    else:
        break
Another option is a for loop instead of a while loop.

for _ in range(5): # Will loop exactly 5 times
  answer1 = input("Password: ")
  if answer1 != "123":
    print("Wrong Password")
    continue
  else:
    print("Welcome!")
    break