(very new to programming) Trying to add a attempt counter to this While loop via subtracting variables

I was making a program that uses a while loop and if operators that gives the user 3 attempts to write a password, im trying to add an attempt counter that displays how many attempts you have left by subtracting the variables

I tried using a variable: Attempts_left to give me the number of attempts left by subtracting Max_attempts by Attempt_ count

super_password = "survive"
attempt = ""
Attempt_count = 0
Max_attempts = 3
Attempts_left = Max_attempts-Attempt_count
Out_of_attempts = False

while super_password != attempt and not(Out_of_attempts):
    if Attempt_count < Max_attempts:
        Attempt_count += 1
        attempt = input("Enter password, " + str(Attempts_left) + " attempts left: ")


    else:
        Out_of_attempts = True
if Out_of_attempts:
    print("Access denied")
else:
    print("Access granted")

But it would always display: Enter password, 3 attempts left:

>Solution :

Here’s an updated version of your code that should work as you intended:

super_password = "survive"
attempt = ""
attempt_count = 0
max_attempts = 3
out_of_attempts = False

while super_password != attempt and not(out_of_attempts):
    attempts_left = max_attempts - attempt_count
    if attempt_count < max_attempts:
        attempt_count += 1
        attempt = input("Enter password, " + str(attempts_left) + " attempts left: ")

    else:
        out_of_attempts = True
if out_of_attempts:
    print("Access denied")
else:
    print("Access granted")

The issue in your original code is that you were defining the Attempts_left variable before the loop starts, and you were not updating it inside the loop. Therefore, it always remained the same value (3). In the updated version, I moved the definition of attempts_left inside the loop and updated it before each input request. This way, it will be calculated based on the current attempt_count value and will always be accurate.

Leave a Reply