Retry a Flaky Operation

Hard ⏱ 18 min 30% acceptance ★★★★★ 4.8
Write retry(func, attempts) that calls the zero-argument func() up to attempts times, returning its result on the first success. If every attempt raises, re-raise the last exception. No sleeping needed — this is about the control flow.

Examples

Example 1
Input
retry(flaky, 3)  # fails twice then returns 'ok'
Output
'ok'
Explanation

Third attempt succeeds; earlier exceptions are swallowed.

Constraints

  • At most attempts calls.
  • Re-raise the final exception if all fail.

Topics

Exception Handlingretry loop

Companies

AmazonNetflixUber

Hints

Hint 1

Save the exception in a variable in the except block.

Hint 2

A bare raise inside except also works on the last iteration.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.