Loops in Python: for, while, break, continue and enumerate()

Computers excel at doing repetitive tasks thousands of times without getting tired or making copy-paste mistakes. Whether you need to ping a list of 50 servers, scan every line in an access log or retry a failed database connection up to three times, you use loops. Python provides two loop structures—for and while—along with helper functions like range() and enumerate() that keep loop code clean and readable.

When to Use for vs while

Loop Type How It Works Best Used When
for loop Steps through each item in a sequence or iterable one by one until the collection ends You have a known collection of items (a list of servers, lines in a file) or a fixed number of repetitions
while loop Repeats as long as a boolean condition remains True You do not know in advance how many iterations are needed (polling a job status or waiting for valid input)

The for Loop and range()

servers = ["srv-web-01", "srv-web-02", "srv-db-01"]

for hostname in servers:
    print(f"Running security patch check on {hostname}...")

# Repeat an action 3 times (stop value 4 is excluded)
for attempt in range(1, 4):
    print(f"Connection attempt #{attempt}")

Tracking Position Cleanly With enumerate()

Wrap any sequence in enumerate(iterable, start=1) to receive both the counter and the item simultaneously without manual index math:

tasks = ["Verify backup integrity", "Rotate API keys", "Update firewall rules"]

for step_number, task in enumerate(tasks, start=1):
    print(f"Step {step_number}: {task}")

Controlling Loop Execution: break and continue

  • continue: Immediately skips the rest of the current iteration and jumps to the next item.
  • break: Immediately exits the entire loop altogether.
log_entries = [
    "INFO: Service started",
    "# Comment line to ignore",
    "FATAL: Database disk full - halting scan",
    "INFO: Heartbeat OK"
]

for line in log_entries:
    if line.startswith("#"):
        continue  # Skip comment lines
    if "FATAL" in line:
        print(f"Critical failure found -> {line}")
        break     # Stop scanning further lines
    print(f"Processed -> {line}")

The while Loop: Polling and Retries

max_retries = 3
attempt = 1
connected = False

while attempt <= max_retries and not connected:
    print(f"Attempt {attempt} of {max_retries}: Connecting...")
    if attempt == 2:
        connected = True
        print("Connection established!")
    attempt += 1

Common Mistakes

  • Forgetting to update the counter in a while loop: Omitting attempt += 1 creates an infinite loop. Press Ctrl + C in your terminal to stop a runaway script.
  • Modifying a list while iterating over it: Removing items inside a for item in my_list: loop shifts indices and skips elements. Loop over a copy (my_list[:]) or use a list comprehension.
  • Off-by-one errors with range(): Remember that range(5) produces 0, 1, 2, 3, 4 (stopping before 5).
Key takeaways
  • Use a for loop to iterate over known sequences; use a while loop when repeating until a condition changes.
  • Prefer for index, item in enumerate(items, start=1): over manual range(len(items)) indexing.
  • Use continue to skip irrelevant items and break to stop searching once your target is found.
  • Always verify that every while loop has a clear exit condition that is guaranteed to be reached.

Related Lessons