If software engineering had a superpower, it would be automation. A computer's ability to repeat a task millions of times per second without fatigue is the foundation of data processing. In Python, we control this immense power using `for` and `while` loops.
1The 'For' Loop and Iterables
In many programming languages, a for loop requires you to manually track a counter variable. Python's for loop is much smarter—it operates on the concept of 'iteration'. You give Python a collection (like a List or a String), and it automatically pulls out one item at a time until the collection is empty.
The syntax is for item in collection:. The item variable is created automatically and holds the current piece of data. If you don't have a collection but just want to loop a specific number of times (e.g., training an AI for 10 epochs), use the range(n) function to generate a sequence of numbers from 0 up to n-1.
# Iterating over a collection
models = ["GPT", "Claude", "Gemini"]
for m in models:
print(f"Loading: {m}")
# Iterating a specific number of times
for i in range(2):
print(f"Epoch {i+1} complete.")Loading: Claude
Loading: Gemini
Epoch 1 complete.
Epoch 2 complete.
2The 'While' Loop and State
While for loops are bounded by the size of a collection, while loops are bounded by a logical condition. A while loop will continue executing its code block repeatedly as long as the condition evaluates to True.
This is ideal for scenarios where you don't know in advance how many iterations are required. For example, you might want to continue training a model *while* the error rate is greater than 5%. However, this comes with a severe risk: if you forget to update the variables inside the loop so that the condition eventually becomes False, the loop will run infinitely and crash your program.
error_rate = 10.0
# Loop continues until error is <= 2.0
while error_rate > 2.0:
print(f"Current Error: {error_rate}%")
# CRITICAL: We must modify the state!
error_rate -= 4.0
print("Target error reached. Stopping.")Current Error: 6.0%
Current Error: 2.0%
Target error reached. Stopping.
3Loop Control (Break and Continue)
Sometimes you need to hijack the normal flow of a loop based on a specific event. Python provides two keywords for this: break and continue.
The break keyword is an emergency exit. If Python hits a break statement, it immediately aborts the entire loop and moves on to the rest of the script.
The continue keyword is a skip button. If Python hits a continue statement, it ignores any remaining code in the *current iteration*, and immediately jumps back up to the top of the loop to process the next item. This is incredibly useful for skipping corrupted data during a large batch process.
data = ["img1", "CORRUPT", "img2"]
for item in data:
if item == "CORRUPT":
print("Found corruption! Skipping...")
continue # Jumps to next item
# This line is skipped when item == "CORRUPT"
print(f"Processing {item}")Found corruption! Skipping...
Processing img2
