Skip to main content
Programming from zero

Retry a connection until it succeeds

mediumLoops

Problem statement

A connection attempt might fail the first time and succeed on a later try. Retrying means looping until either it succeeds, or you've tried too many times, an unlimited retry loop can hang forever if the thing you're waiting on never comes back.

flowchart LR A["attempt = 0"] --> B{"connected or\nattempt >= max?"} B -->|"no"| C["attempt += 1, try again"] C --> B B -->|"yes"| D["stop"] classDef start fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A classDef check fill:#FEF3C7,stroke:#D97706,color:#92400E classDef retry fill:#E0E7FF,stroke:#4F46E5,color:#312E81 classDef stop fill:#D1FAE5,stroke:#059669,color:#065F46 class A start class B check class C retry class D stop

Common mistake: retrying with no limit at all.

TEXT
Wrong: while not connected:

If the connection never succeeds, this loop never ends. A retry loop always needs a cap, some maximum number of attempts, so it eventually gives up and reports failure instead of hanging forever.

Your task: simulate retrying a connection that succeeds on the 3rd attempt, with a cap of 5 attempts. Print each attempt as Attempt 1..., Attempt 2..., and so on, then print Connected on attempt 3 once it succeeds.

Expected output:

TEXT
Attempt 1...
Attempt 2...
Attempt 3...
Connected on attempt 3

Approach

Loop while not yet connected and under the attempt cap. Here the connection is simulated as succeeding exactly on attempt 3:

attempt = 0
max_attempts = 5
connected = False

while not connected and attempt < max_attempts:
    attempt += 1
    print(f"Attempt {attempt}...")
    if attempt == 3:
        connected = True

if connected:
    print(f"Connected on attempt {attempt}")
else:
    print(f"Failed after {max_attempts} attempts")