Programming from zero

Retry a connection until it succeeds

mediumLoops

Problem statement

A script retries a connection up to max_attempts times and stops as soon as one works. Simulate the results with a list, results = [False, False, True], where each item is the outcome of one attempt.

For each attempt, print Attempt N: failed or Attempt N: success, and stop after the first success. If every attempt fails, print Giving up at the end.

Examples

Example 1

Input: max_attempts = 5 results = [False, False, True]

Output: Attempt 1: failed Attempt 2: failed Attempt 3: success

Hints

Approach

Optimal

A while loop repeats while its condition is true, which suits retries because you do not know in advance how many passes you need. The counter attempt starts at 1 and grows by 1 each pass; the condition also stops when the simulated results run out. When an attempt succeeds, break leaves the loop immediately. Python loops can have an else: block, which runs only if the loop ended without break, so it is the natural place for Giving up. In a real script, results[attempt - 1] would be replaced by an actual connection check, and you would usually add time.sleep() between attempts.

Python
max_attempts = 5
results = [False, False, True]
attempt = 1
while attempt <= max_attempts and attempt <= len(results):
if results[attempt - 1]:
print(f"Attempt {attempt}: success")
break
print(f"Attempt {attempt}: failed")
attempt += 1
else:
print("Giving up")

Follow-up questions

  • Double a delay variable after each failure (1, 2, 4, ...) and print it; this is called exponential backoff.

Frequently asked questions

You probably forgot attempt += 1, so the condition never becomes false. This is called an infinite loop; press Ctrl+C to stop it, then make sure something inside the loop moves it toward the end.

List positions start at 0, but humans count attempts from 1. Subtracting 1 converts the attempt number into a list position.