For & While Loops/shaare/VAK_8g
For & While Loops
Python provides two main ways to repeat actions: for loops (for iterating over known sequences) and while loops (for repeating as long as a condition is true). These are essential for automating repetitive tasks in DevOps, such as processing lists of servers, retrying operations, or polling for status changes.
Automating Repetition: Loops
forloop: Iterates through each item in a known sequence (list, tuple, string, dictionary items, range, file lines). Best when you know the items to process.whileloop: Repeats as long as a condition remainsTrue. Best when the number of repetitions isn't known beforehand, but a stopping condition is.
for Loops: Processing Each Item
for loops are used to process each item in a sequence. The loop variable takes on the value of each item, one at a time, and the indented block runs for each item.
servers = ["web01", "web02", "web03"]
for server in servers:
print("Pinging server:", server)
for char in "SUCCESS":
print(char)
for idx in range(10):
print("Pinging server:", idx)
while Loops: Repeating While True
while loops repeat a block of code as long as a condition remains True. This is useful when you don't know in advance how many times you'll need to repeat the action.
connection_attempts = 0
max_attempts = 5
connected = False
while not connected and connection_attempts < max_attempts:
print(f"Attempting to reach server: {connection_attempts + 1}")
# Simulating for the purposes of demonstration - Succeeds on 4th attempt
if connection_attempts == 3:
connected = True
connection_attempts += 1
if not connected:
print("Failed to connect after maximum attempts.")
Important: The code inside the while loop must eventually make the condition False (e.g., by incrementing a counter or changing a flag), or you'll create an infinite loop.
Controlling Loop Flow: break and continue
break: Immediately exits the innermost loop. Useful when you've found what you need or hit an error.continue: Skips the rest of the current iteration and moves to the next one. Useful for skipping items that don't meet criteria.
users = ["guest", "tester", "admin01", "admin02", "dev01"]
found_admin = None
for user in users:
print(f"Checking user: {user}")
if user.startswith("admin"):
found_admin = user
print(f"Admin user found: {found_admin}. Stopping search.")
break
filenames = ["nginx.conf", "app.yaml", "db.yaml", "notes.txt"]
for file in filenames:
if not file.endswith(".yaml"):
print(f"Skipping non-yaml file: {file}")
continue
print(f"Processing YAML config: {file}")
(97)