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