← Previous Module 3: Looping (While Loops) Next →
Statement
Solution

Python Exercise 3.3: Password Retry

Create a security checkpoint using a while loop.

Your program should:

  • Set a correct password (e.g., "secret").
  • Allow the user 3 attempts to enter the password.
  • If they enter it correctly, print "Access Granted" and exit the loop.
  • If they enter it incorrectly 3 times, print "Locked Out".

Note for this Compiler: Since this code runs in one go, please enter multiple guesses in the "Custom Input" box on separate lines (e.g., 3 wrong passwords or 1 right one).

Sample Interaction:

Input (Multiple Lines)
Output
wrong1 wrong2 wrong3
Enter password: wrong1 Enter password: wrong2 Enter password: wrong3 Locked Out

Solution

We use a counter variable to track attempts and the break statement to exit the loop early if successful.

# 1. Setup correct_pass = "secret" attempts = 0 # 2. While loop runs while attempts are less than 3 while attempts < 3: guess = input("Enter password: ") if guess == correct_pass: print("Access Granted") break # Exit loop immediately else: attempts = attempts + 1 # Increment counter # 3. Check if locked out if attempts == 3: print("Locked Out")

Key Concepts:

  • while condition: runs as long as the condition is True.
  • break stops the loop immediately.
  • input() inside a loop asks for data repeatedly.
Python 3
Test Console
Run code to see output...
Scroll to Top