[Python Series 4] Control Flow with Conditionals and Loops

한국어 버전

Now that you've stored and retrieved data, it's time to decide when and how to process it. Conditionals and loops are the core flow-control tools—and the most common constructs inside automation scripts. We'll cover if, for, and while through realistic scenarios.

Key terms

  1. Control flow: The logic that determines the order in which code executes.
  2. Iterable: Any object you can loop over, such as lists, tuples, or dictionaries.
  3. enumerate: A built-in that yields both the index and the value during iteration.
  4. break / continue: Keywords that stop a loop entirely or skip the current iteration.

Core ideas

Study memo

  • Time required: 45–60 minutes
  • Prereqs: Variables, data types, and experience running scripts with uv
  • Goal: Combine branching and looping patterns that can be reused in automation scripts

Conditionals branch behavior; loops repeat actions. With both tools, you can model nearly any automation flow.

Code examples

Conditionals

temperature = 29

if temperature >= 30:
    print("Air conditioner: high mode")
elif temperature >= 25:
    print("Air conditioner: low mode")
else:
    print("Ventilation is enough")

Python evaluates conditions top to bottom and only runs the first true block. Use logical operators (and, or, not) to compose more complex checks.

for loops

Ideal when iterating over iterables like lists or tuples.

logs = [
    {"status": 200, "path": "/health"},
    {"status": 500, "path": "/sync"},
    {"status": 200, "path": "/users"},
]

for log in logs:
    if log["status"] >= 400:
        print(f"⚠️ Error at {log['path']}")

Pair with enumerate() to get both the index and the item.

for index, todo in enumerate(["Report", "Deploy", "Meeting"]):
    print(index, todo)

List comprehensions

Condense looping plus conditional filtering into one line that builds a new list.

numbers = [1, 2, 3, 4, 5]
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
print(even_squares)  # [4, 16]

while loops

Use when the number of iterations isn't fixed and depends on a condition.

countdown = 5

while countdown > 0:
    print(countdown)
    countdown -= 1

print("Auto deployment starts")

Ensure the exit condition will eventually be met to avoid infinite loops.

break and continue

  • break: exit the loop entirely.
  • continue: skip to the next iteration.
for status in [200, 200, 500, 200]:
    if status == 500:
        print("Error detected, stopping monitoring")
        break
    print("All good")

Mini project: simple inventory checker

inventory = {
    "keyboard": 12,
    "mouse": 0,
    "monitor": 3,
}

alert_items = []

for name, count in inventory.items():
    if count <= 1:
        alert_items.append(name)

if not alert_items:
    print("All products have enough stock")
else:
    print("Restock needed:")
    for item in alert_items:
        print(f"- {item}")

This combines a for loop with conditionals to print only the low-stock products.

Practical example: async API retry logic

Real services must retry failed requests selectively. Combine conditionals and loops like this:


async def fetch_with_retry(url: str, retries: int = 3):
    for attempt in range(1, retries + 1):
        response = await httpx.AsyncClient().get(url, timeout=5)
        if response.status_code == 200:
            return response.json()
        if attempt == retries:
            raise RuntimeError("Max retries exceeded")
        await asyncio.sleep(2 * attempt)

data = asyncio.run(fetch_with_retry("https://school-api.example.com/health"))
print(data)

You'll revisit this pattern in the Requests/Automation post, and it will feel natural if you've already mastered the control-flow pieces.

Why it matters

Conditionals and loops power everything from retrying API calls to generating monitoring reports—tasks you can use in school clubs today. Once these flows feel natural, it's easier to decide how to split functions and modules in the next step.

Practice

  • Follow along: Rebuild the inventory checker, swap item names, and adjust the messages.
  • Extend: Use continue to skip status == 200 logs in a simple monitoring script.
  • Debug: Remove a while exit condition to create an infinite loop, then fix it by decrementing counters or adding break.
  • Definition of done: You write at least two branching flows and can explain how execution moves through them.

Wrap-up

Conditionals and loops steer your program. Once you can iterate over data and branch on conditions, splitting the logic into functions becomes straightforward. That's exactly what we'll tackle next.

💬 댓글

이 글에 대한 의견을 남겨주세요