Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Connexion

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}")
3 months ago Permalien
cluster icon
  • Filesystem Paths : Working with Filesystem Paths in Python Manipulating paths as plain strings is error-prone and OS-specific. pathlib provides an object-oriented, cr...
  • List : Lists (list) Lists are ordered, mutable sequences defined with square brackets []. You can add, remove, or change items after creation. Characteristic...
  • 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...
  • Handling Authentication : Handling Authentication APIs often require authentication to control access, rate limits, and auditing. Without authentication, requests to protected...
  • Handling Subprocess Errors : Handling Subprocess Errors External commands can fail in multiple ways: non-zero exit codes, missing executables, or hanging processes. Using subpr...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli