Loops & Iteration

3 min read

Making Python Repeat Work – The Smart Way

In programming, loops help us run code repeatedly without writing the same lines again and again. Whether it’s going through a list, repeating a task until a condition is met, or retrying something a few times—loops are essential.

Let’s dive deep into how Python handles repetition.

1. 🎯 for and while Loops #

for Loop #

Used when you want to iterate over a sequence (like a list, string, or range).

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

You know how many times you’re looping? Use for.


🔄 while Loop #

Runs as long as a condition is True.

count = 1
while count <= 5:
    print("Count:", count)
    count += 1

You don’t know how many times you’ll loop? Use while.


2. 📦 Using range() and Iterables #

🔢 range() Function #

range(start, stop, step) gives you a sequence of numbers.

for i in range(1, 6):
    print(i)
  • range(5) → 0 to 4
  • range(2, 10, 2) → 2, 4, 6, 8

🔁 Iterables #

Strings, lists, tuples, dictionaries, etc., are all iterables—you can loop through them.

for letter in "Hannan":
    print(letter)

3. 🛑 break, continue, and pass #

🧨 break #

Exits the loop entirely.

for i in range(5):
    if i == 3:
        break
    print(i)  # prints 0, 1, 2

continue #

Skips the current loop iteration.

for i in range(5):
    if i == 2:
        continue
    print(i)  # prints 0, 1, 3, 4

🚧 pass #

A placeholder. Does nothing—useful when code is “coming soon”.

for i in range(3):
    pass  # to be implemented later

4. 🧱 Nested Loops #

A loop inside another loop is called a nested loop.

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

Great for:

  • Working with 2D arrays
  • Printing patterns
  • Comparing items in two lists

🔐 Real-World Use Case: Password Validator with Retry Limit #

Let’s build a script that:

  • Asks the user to enter a password
  • Validates it against a saved password
  • Allows up to 3 attempts
  • Locks the user out after failed attempts

✅ Requirements: #

  • Loop with retry count
  • Input validation
  • Use of break, continue

💻 Full Code Example: #

# Predefined password
correct_password = "python123"
max_attempts = 3
attempts = 0

print("🔐 Welcome to Secure Login System")

while attempts < max_attempts:
    entered_password = input("Enter your password: ")

    if entered_password == "":
        print("⚠️ Password cannot be empty. Try again.")
        continue

    if entered_password == correct_password:
        print("✅ Access Granted!")
        break
    else:
        attempts += 1
        remaining = max_attempts - attempts
        print(f"❌ Incorrect password! Attempts left: {remaining}")

        if remaining == 0:
            print("🔒 You are locked out. Try again later.")

🔍 What This Covers: #

FeatureDemonstrated In Code
while loopTo repeat login attempts
breakOn successful login
continueWhen input is empty
Password check logicWith conditionals
Counter logicRetry limiter

🧠 Challenge Ideas: #

  • 🔁 Allow user to reset the password if they know a secret key.
  • ⏳ Add a time delay (using time.sleep()) between retries.
  • 🧮 Log the number of failed attempts and show it at the end.
  • 🛡 Encrypt password using hashlib.

🧩 Summary #

In this section, you learned:

for and while loops
✅ Iterating with range() and iterables
✅ Using break, continue, and pass
✅ How to build a real-world retry mechanism with loops
✅ The basics of building a secure CLI login system


✨ What’s Next? #

Up next in the series:

🧰 Functions & Modular Coding
Creating reusable code blocks, parameters, return values, scope, and a use case like a Unit Converter Tool

Want me to write the next one now? Or turn all this into a PDF, blog, or APEX Learning App version? Let me know!

Updated on June 9, 2025