Control stopping, retries, and recovery
Prevent runaway loops and handle timeouts, errors, and repeated failures.
- Choose explicit stop conditions, retry limits, and recovery paths.
A reliable loop defines how success is detected, when it should stop, and what happens after failure. Set limits on iterations, elapsed time, and resource use. Retry only when the error may be transient and the action is safe to repeat. If the loop cannot make progress, preserve useful state and return a clear handoff instead of repeating the same failed step.
A small example
1max_steps = 4
2for step in range(1, max_steps + 1):
3 print(f"Step {step}: check progress")
4 if step == 2:
5 print("Goal met; stop")
6 breakStep 1: check progress Step 2: check progress Goal met; stop
A timeout does not always mean an action failed; it may have completed without the caller receiving the response. Use idempotency keys or check the external state before retrying a non-idempotent operation. Log the reason for stopping so both people and operators can understand the outcome.
Key takeaways
Choose explicit stop conditions, retry limits, and recovery paths.
Bound the loop, validate actions, and make its outcome observable.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…