Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

For & While Loops/shaare/VAK_8g

  • python
  • python

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

  • for loop: Iterates through each item in a known sequence (list, tuple, string, dictionary items, range, file lines). Best when you know the items to process.
  • while loop: Repeats as long as a condition remains True. 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}")
2 months ago Permalink
cluster icon
  • Python Functions Are First‑Class Citizens : Python Functions Are First‑Class Citizens In Python, functions behave like any other object (strings, ints, lists). Because they are "first‑clas...
  • Logging to Files : Logging to Files Basic File Logging with FileHandler Use logging.FileHandler to write log records to a file. mode='a' (append) preserves existing log...
  • Working with JSON files : Working with JSON files JSON is the standard format for data exchange in web services and cloud APIs. Python’s built-in json module provides function...
  • Numbers, strings : Numbers (int and float) int: Whole numbers (e.g., 10, 1024). No overflow due to arbitrary precision. float: Numbers with decimals (e.g., 3.14159). Us...
  • Editable Installs with pyproject.toml : Editable Installs with pyproject.toml The Python interpreter doesn't automatically know about our project's structure. The modern and most robust solu...


(97)
Filter untagged links
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community