If you write while True: without a break condition, your script runs forever. Always ensure while loops will eventually exit. Test loops locally before running in production—hung processes consuming CPU are a common production incident.
Control Flow, Conditionals, and Loops
Master if/elif/else to make decisions, use for and while loops to iterate over data, and structure decision logic that mirrors real-world automation scenarios.
🧒 Simple Explanation (ELI5)
A script is like a recipe. Sometimes you check an ingredient: "If we have eggs, add them; else use milk instead." That is a conditional (if/else). Sometimes you repeat a step: "Stir the soup for 5 minutes" means keep stirring multiple times until time is up—that is a loop. Conditionals and loops let scripts make decisions and automate repetition instead of doing the same thing once.
🔧 Why Do We Need Control Flow?
- Decisions: scripts need to handle different scenarios (if CPU is high, alert; else, continue normally).
- Repetition: loops process multiple items (all servers, all log entries) without copy-pasting code.
- Automation: the whole point of scripts is to automate—conditionals and loops are the foundation of automation logic.
- Error handling: you check if operations succeed before proceeding to the next step.
⚙️ Technical Explanation
Conditionals test a condition and execute code based on the result. Loops repeat code while or until a condition is true, or iterate over a collection.
if/elif/else: execute a code block if a condition is True. for loop: iterate over a sequence (list, string, range). while loop: repeat while a condition is True. break/continue: control loop execution (exit early or skip to next iteration).
⌨️ Control Flow Patterns
# ===== IF / ELIF / ELSE =====
cpu_usage = 85.5
if cpu_usage > 90:
print("CRITICAL: CPU overloaded")
elif cpu_usage > 70:
print("WARNING: CPU high")
else:
print("OK: CPU normal")
# ===== FOR LOOPS =====
servers = ["web01", "web02", "api01"]
# Iterate over list
for server in servers:
print(f"Checking {server}")
# Iterate with index
for i, server in enumerate(servers):
print(f"Server {i}: {server}")
# Iterate over range
for i in range(5): # 0, 1, 2, 3, 4
print(f"Attempt {i}")
for i in range(1, 4): # 1, 2, 3
print(f"Step {i}")
# ===== WHILE LOOPS =====
retry_count = 0
max_retries = 3
while retry_count < max_retries:
print(f"Attempt {retry_count + 1}")
# Try operation here
success = False # assume failure for demo
if success:
print("Success!")
break # exit loop early
retry_count += 1
if retry_count == max_retries:
print("Failed after all retries")
# ===== CONTINUE AND BREAK =====
for server in servers:
if server == "api01":
print(f"Skipping {server}")
continue # skip to next iteration
print(f"Processing {server}")
# ===== LIST COMPREHENSION (Pythonic shortcut) =====
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers] # [1, 4, 9, 16, 25]
# Filter with list comprehension
working_servers = [s for s in servers if s != "api01"]
# ===== REAL-WORLD PATTERN: SAFE API POLLING =====
attempt = 0
max_attempts = 5
delay_seconds = 2
while attempt < max_attempts:
try:
# API call would go here
print(f"Attempt {attempt + 1}: Calling API...")
response_ok = False # would be true if API succeeded
if response_ok:
print("API succeeded")
break
except Exception as e:
print(f"Error: {e}")
attempt += 1
if attempt < max_attempts:
print(f"Retrying in {delay_seconds} seconds...")
# import time; time.sleep(delay_seconds)
print(f"Final status: {'Success' if attempt < max_attempts else 'Failed after retries'}")
💼 Example (Real-world Use Case)
A monitoring script loops through a list of Kubernetes pods, checking each one's status. For each pod, it checks if it is running. If not running, it increments an alert counter and logs the pod name. After checking all pods, it outputs: "All pods healthy" or "ALERT: X pods not running." This combines loops (iterate pods) with conditionals (check status) and decision logic (what to report).
🧪 Hands-on
- Create a list of service names and their status (running/stopped).
- Loop through and print each service name with its status.
- Count how many are running and how many are stopped.
- Print an alert if any service is stopped.
- Write a while loop that retries an operation up to 3 times (simulate with a counter).
Write a script that: (1) loops from 1 to 10, (2) skips multiples of 3 (using continue), (3) stops when it reaches 7 (using break), (4) prints "Processing: X" for all others. Expected output: 1, 2, Process 4, 5, Process 7.
🐛 Debugging Scenario
Problem: your script hangs and uses 100% CPU.
- Cause: likely an infinite loop (while condition never becomes False) or a condition that is never met so break is never called.
- Diagnose: add print statements before and after the loop to see if it enters and exits. Use Ctrl+C to kill the script. Check loop conditions: are they guaranteed to eventually be false/true?
- Fix: add a safety counter to any while loop, ensure break conditions can actually be reached, test locally with small datasets before running on full production data.
🎯 Interview Questions
Beginner
for loops iterate over a sequence (list, range) a fixed number of times. while loops repeat as long as a condition is true. Use for loops when iterating a collection; use while loops when you need to repeat until a condition is met (retries, polling). for loops are safer because they do not risk infinite loops.
break exits the loop immediately, even if the loop condition has not been met. A common pattern: retry a network operation in a loop, and break as soon as it succeeds, rather than continuing to retry unnecessarily.
continue skips the rest of the current iteration and jumps to the next one. Useful to skip unwanted items: "if server is blacklisted, continue; else process the server."
Scenario-based
Use a for loop from 1 to 6 (or while with a counter). Inside, attempt the operation in a try/catch. If success, break immediately. If exception, check if this is the last attempt—if so, raise; else continue to next attempt. Use time.sleep(10) between attempts.
🌐 Real-world Usage
Ansible loops through hosts applying tasks. Kubernetes controllers loop through pods checking status. CI/CD pipelines loop through deployment stages with conditionals for approval gates. Logging scripts loop through log files filtering by severity. Control flow is everywhere in DevOps automation.
📝 Summary
if/elif/else make decisions based on conditions. for loops iterate over sequences, while loops repeat until a condition is met. break exits early, continue skips to the next iteration. List comprehensions offer Pythonic shortcuts. Pattern: loop through data, check conditions, take actions. These are the building blocks of all automation scripts.