Python Loops
💡
Exercise 17

Enter PIN 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

Welcome to Chapter 4: Loops! 🔄

💡 Think of it like this: A loop is like a merry-go-round — it keeps going around and around until we tell it to stop. A while loop keeps running as long as a condition is True.

# A while loop keeps going until the condition is False count = 0 while count < 3: print(f'Count is: {count}') count += 1 # Don't forget this! Without it, infinite loop! # Output: # Count is: 0 # Count is: 1 # Count is: 2

Key concepts:

  • 🔄 while loops run as long as the condition is True
  • 🛑 break — exits the loop immediately
  • continue — skips to the next iteration
  • ⚠️ Always make sure the condition eventually becomes False, or you get an infinite loop!

This exercise simulates a PIN entry system — the loop keeps asking until the correct PIN is entered (or max attempts reached).

📋 Instructions
Create a variable `pin` set to `0` and `correct_pin` set to `1234`. Use a while loop that keeps asking for a PIN. Since we can't use `input()` in this editor, simulate 3 wrong guesses then the correct one: ```python pin = 0 correct_pin = 1234 attempts = 0 while pin != correct_pin: attempts += 1 if attempts < 4: pin = 0000 print('Incorrect PIN.') else: pin = 1234 print('PIN accepted!') ``` Expected output: ``` Incorrect PIN. Incorrect PIN. Incorrect PIN. PIN accepted! ```
Use a while loop with a counter. Increment attempts each iteration. When attempts reaches 4, set pin to the correct value.
⚠️ Try solving it yourself first — you'll learn more!
# A while loop keeps going until the condition is False
count = 0
while count < 3:
    print(f'Count is: {count}')
    count += 1  # Don't forget this! Without it, infinite loop!
# Output:
# Count is: 0
# Count is: 1
# Count is: 2
🧪 Test Cases
Input
Run your code
Expected
Incorrect PIN. Incorrect PIN. Incorrect PIN. PIN accepted!
Expected program output
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.