Control flow and loops
Every AI agent runs in a loop: check a condition, take an action, repeat. The while loop in an agent framework is the same while loop you will learn here. Let us master control flow.
Python control flow
How if/elif/else branching and loops work
# if / elif / else
review_score = 4
if review_score >= 4:
print("Great review!")
elif review_score >= 2:
print("Average review")
else:
print("Poor review")
# Checking membership with `in`
dangerous_commands = ["rm -rf /", "sudo", "shutdown"]
user_command = "ls -la"
if any(d in user_command for d in dangerous_commands):
print("Blocked!")
else:
print(f"Safe to run: {user_command}")
# Ternary expression (inline if/else)
api_key = ""
status = "configured" if api_key else "missing"
print(f"API key: {status}")if/elif/else branches your logic. The ternary expression (x if condition else y) is a common pattern for setting defaults in one line.
any() returns True if at least one item in the iterable is True. It combines a loop and a condition check into one line. Here it checks if any dangerous command appears in the user input. You will see this pattern in guardrails for AI agents.
# for loops
menu = ["Avocado Toast", "Quinoa Bowl", "Mac & Cheese"]
for item in menu:
print(f"- {item}")
# enumerate gives you index + value
for i, item in enumerate(menu):
print(f"{i + 1}. {item}")for loops iterate over collections. enumerate() gives you both the index and the value, which is useful when you need to number items.
Python has a unique feature: else after a while loop. The else block runs only if the loop completes without hitting break, making it perfect for retry patterns in AI agents where it handles the "all attempts failed" case.
# while loops (the agent loop pattern!)
iteration = 0
max_retries = 3
while iteration < max_retries:
print(f"Attempt {iteration + 1}")
iteration += 1
if iteration == 2:
print("Success! Breaking early.")
break
else:
# Runs ONLY if the loop finished without break
print("All attempts exhausted")while loops repeat until a condition is false, and break exits early. The else block runs only if no break occurred, which is how AI agents implement retry logic.
Great question! Python has exactly that: comprehensions. They let you write a loop, a transformation, and a filter all in one line.
Quiz: Quiz
Loading practiceโฆ