3.2.2 Preventing Infinite Loops

Unit: Unit 3: Loops • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Drain a token bucket until tokens are exhausted
tokens = 4

while tokens > 0:
    print("Dispensing item. Tokens remaining:", tokens)
    # Essential: decrement tokens toward the terminating condition (tokens == 0)
    tokens -= 1

print("Bucket empty. Machine locked.")
Open in Live Interactive Python Sandbox →