Lesson contents

Python — Post-test loops with while True

Python models a post-test loop by entering while True and checking for a break after performing the required first operation.

A simple example

Print first, then test

  1. Start with n starts at 1
  2. Do this Print n, add 1
  3. Result Stop at 4
The first print happens before the stopping test. The loop prints 1, 2 and 3 on separate lines.
lesson.py
n = 1
while True:
    print(n)
    n += 1
    if n > 3:
        break
Output
1
2
3
Advertisements

Poll until ready or the attempt limit

Count the first poll for every request, even if it is already ready. Stop after success or after the configured maximum number of attempts. The attempt limit is positive. Once either success or the limit is reached, break leaves the loop and the function returns the number of polls.

First check: Busy. Second check: Ready. Checks made: 2.
Check a printer until it is ready

A print desk checks the printer once before deciding whether to check again. If the printer answers ready on the second check, the loop stops there. A limit of three checks keeps an offline printer from holding up the desk.

Run the example

Use Python 3.9 or later. Run these commands from the directory containing the example.

python3 lesson.py
lesson.py
def poll_count(ready_on, limit):
    attempts = 0
    while True:
        attempts += 1
        if attempts >= ready_on or attempts >= limit:
            break
    return attempts

for ready_on, limit in ((5, 1), (2, 3), (8, 3)):
    print(poll_count(ready_on, limit))
Output
1
2
3

With one permitted attempt, the first case stops at 1. The second becomes ready on attempt 2. The last case never reaches readiness within its three-attempt limit.

Apply the loop to a retry queue

Simulate a job using prerecorded replies. T means a temporary failure, S means success, and X means permanent rejection. Process at most two replies per job. Stop on S or X and report how many replies were consumed.

First reply: Temporary failure. Next reply: Success. Attempts used: 2.
Handle a temporary print failure

A queue can retry a temporary failure once under a two-attempt limit. A temporary failure followed by success finishes the job. A permanent rejection stops the job immediately and leaves the next reply unused.

Run this example

Save this program as lesson.py and run it separately.

python3 lesson.py
lesson.py
def process(responses, limit):
    used = 0
    for response in responses:
        if used == limit:
            break
        used += 1
        if response == "S":
            return "sent", used
        if response == "X":
            return "rejected", used
    outcome = "limit reached" if used == limit else "no response"
    return outcome, used

jobs = {"A": "TS", "B": "XS", "C": "TTS", "D": ""}
for job, responses in jobs.items():
    outcome, attempts = process(responses, 2)
    print(f"{job}: {outcome} ({attempts})")
Output
A: sent (2)
B: rejected (1)
C: limit reached (2)
D: no response (0)

Job A succeeds on its second reply. B stops at the rejection before its later success. C reaches the attempt limit with a success still unread. D has no recorded reply, so its count stays zero. Try raising the limit to three: only C changes, succeeding on the third reply.

Try it yourself

A request is ready on the first poll and allows three attempts. How many polls run?

Check your answer

Exactly one. The success check happens after the first poll. The example assumes a positive attempt limit.

Python language documentation

Related tags

  • Python
  • post-test loops
  • retries
  • termination