Exercise 9: Retry a Flaky Call — Possible Solution ==================================================================== MAX_ATTEMPTS = 5 def fetch(attempt): if attempt < 3: raise ConnectionError("server not ready") return "data from server" for attempt in range(1, MAX_ATTEMPTS + 1): try: result = fetch(attempt) print(f"Attempt {attempt}: success -> {result}") break except ConnectionError as error: print(f"Attempt {attempt}: failed ({error})") else: print(f"Giving up after {MAX_ATTEMPTS} attempts") Example run: Attempt 1: failed (server not ready) Attempt 2: failed (server not ready) Attempt 3: success -> data from server Same program with MAX_ATTEMPTS = 2: Attempt 1: failed (server not ready) Attempt 2: failed (server not ready) Giving up after 2 attempts WHY THIS WORKS AS AN ANSWER ------------------------------ If fetch() raises, Python jumps straight to the except block, so the print and the break after the call are skipped and the loop goes round again. If fetch() returns normally, the success message prints and break ends the loop; that also skips the else block. Only when every attempt raises does the loop run out of passes, and then the for loop's else runs. With MAX_ATTEMPTS = 2 the function never gets as far as attempt 3, so the give-up message appears. In a real service you would normally also wait a little between attempts.