Retry a connection until it succeeds
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.
Common mistake: retrying with no limit at all.
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:
Attempt 1...Attempt 2...Attempt 3...Connected on attempt 3Approach
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")