Introduction
Imagine having to manually type out a thousand welcome emails or review a million lines of financial transactions one by one. It would be exhausting. Computers excel at doing repetitive tasks without getting tired, and in Python, we use loops to unlock this automation. Loops tell your program to run a specific block of code over and over again instantly, transforming manual data entry into a single click.
1. The Two Types of Loops
Python gives us two primary ways to repeat code, depending on whether we know how many times we need to loop beforehand.
The for Loop
You use a for loop when you have a definite starting and ending point, like a list of items or a specific count. It goes through a collection one item at a time until it reaches the end.
Code snippet:
# Looping through a pre-made list
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
print(f"Processing: {fruit}")
Output
The while Loop
You use a while loop when you don’t know exactly how many times you will need to repeat, but you know you want to keep going while a certain condition remains True.
Warning: You must make sure the condition eventually becomes False, or your program will get stuck in an "infinite loop" and freeze!
Code snippet:
countdown = 3
while countdown > 0:
print(countdown)
countdown = countdown - 1 # Updates the condition
print("Blast off!")
Output
2. Upgrading Your Loops
Sometimes you need finer control over how a loop behaves while it is running. Python provides built-in tools to change a loop's path or count its steps.
break and continue (The Steering Wheel)
break: This completely stops the loop immediately and jumps out of it, even if the loop wasn't finished. It is perfect for stopping a search early once you find what you need.
Code snippet:
while True:
name = input('Enter your name (or type quit): ')
if name == 'quit':
break
print(f'Hello, {name}')
Output: This loop will still run until you type the input quit.
continue: This skips the rest of the current turn and jumps straight to the start of the next turn. It is useful for skipping over bad or unneeded data.
Code snippet:
for number in:
if number == 3:
continue # Skip 3
print(number) #Output ; 1,2,3,4,5 #3 is skipped
Output:
Difference between break and continue
| Feature | break |
continue |
|---|---|---|
| Definition | Immediately terminates the entire loop. | Skips the current iteration and moves to the next iteration. |
| Purpose | Stop a loop completely when a condition is met. | Skip a particular item without stopping the loop. |
| Effect on loop | Exits the loop immediately. | Keeps the loop running. |
| Next iteration | Does not execute. | Executes if another iteration is available. |
| Execution afterward | Continues with the first statement after the loop. | Returns to the loop to process the next iteration. |
| Common use case | Stop searching when an item is found or a critical condition occurs. | Skip invalid, unwanted, or irrelevant data. |
| Example condition | if badge == "STOLEN_BADGE": break |
if "Guest" in badge: continue |
| Effect in the badge example | Stops processing at Entry #4 when a stolen badge is detected. | Skips normal employee logging for Entry #2 (Guest_Pass). |
| Employee_Jordan (Entry #5) | Not processed after break at Entry #4. |
Would be processed if the stolen badge condition used continue instead. |
| Works with | Both for and while loops. |
Both for and while loops. |
enumerate() (The Step Counter)
Normally, a for loop only gives you the item itself. If you also need to know the tracking number or position (index) of that item, you wrap your list inside enumerate().
Note: Python starts counting positions at 0 instead of 1.
Code snippet:
tasks = ["Email client", "Update spreadsheet", "Call manager"]
for index, task in enumerate(tasks):
print(f"Task #{index + 1}: {task}")
Output:
3. Practical Example: The Automated Security Badge Scanner
Let's bring all of these concepts together. This program simulates an office security checkpoint. It loops through arriving employees, tracks their entry order, handles guest badges, and completely shuts down if a security threat is detected.
Code snippet:
# --- AUTOMATED CHECKPOINT SCANNER ---
# A list representing badges scanned at the door in order
scanned_badges = ["Employee_Alex", "Guest_Pass", "Employee_Sam", "STOLEN_BADGE", "Employee_Jordan"]
print("--- STARTING DAILY SECURITY LOG ---")
# Using enumerate() to track the entry number alongside the badge name
for entry_number, badge in enumerate(scanned_badges):
# 1. Using 'break' to instantly halt everything for a severe threat
if badge == "STOLEN_BADGE":
print(f"\nCRITICAL WARNING at Entry #{entry_number + 1}!")
print("Stolen badge detected. Locking down all exit doors immediately.")
break # The loop stops dead in its tracks here
# 2. Using 'continue' to skip standard employee logs for guest routing
if "Guest" in badge:
print(f"Entry #{entry_number + 1}: Guest badge detected. Rerouting to front desk...")
continue # Skips the normal logging step below and moves to the next badge
# 3. Normal loop execution for regular employees
print(f"Entry #{entry_number + 1}: {badge} verified. Access granted.")
print("\n--- SECURITY CHECKPOINT SYSTEM PAUSED ---")
Output:
-
The
forLoop: It automatically moves from the first badge to the last badge without needing manual navigation. -enumerate(): It gives us entry_number, allowing us to print clean logs like "Entry #1" and "Entry #2" dynamically. -
break: When it hits the security threat, it completely prevents the rest of the queue (Employee_Jordan) from being evaluated. -**continue**: When it hits the guest pass, it handles the visitor routing but skips printing the "Access granted" line meant only for employees.
Conclusion
Loops are the heavy lifters of programming. By combining for and while loops with steering tools like break, continue, and enumerate(), you can instantly process massive collections of data with minimal code. You have evolved from writing single-file instructions to building powerful, automated pipelines.


Top comments (0)