If, for and while

Run one wallet program with three different balances and watch if, for, while, break, continue and the loop else send it down three different paths.

10 min Free

A program that only runs top to bottom can do one fixed thing. Real programs decide and repeat. if chooses between blocks: Python tests each condition in turn, runs the first block whose condition is True, and skips the rest. elif adds more tests and else catches everything left over.

Two statements repeat. for walks through the items of a list (or any sequence) one at a time. while keeps going as long as a condition stays True, so something inside the loop must eventually change it. Inside either loop, continue skips the rest of the current round and starts the next one, and break leaves the loop at once. Both loops can also have an else block, which runs only when the loop ends without a break.

The program below pays a list of bills from a UPI wallet, tops the balance up if it drops too low, and reports a status. It reads the starting balance from the command line, so the same file takes three different paths. Press Run with a balance of 500, then switch the Try it selector to 150 and 1000 and compare.

Ready
# A UPI wallet pays a list of bills. Run: python3 wallet.py 500
import sys

balance = 500
if len(sys.argv) > 1:
    balance = int(sys.argv[1])
bills = [120, 250, 90]

for amount in bills:
    if amount > 200:
        print("Skip", amount, "(needs OTP)")
        continue
    if amount > balance:
        print("Stop: cannot pay", amount)
        break
    balance -= amount
    print("Paid", amount, "left", balance)
else:
    print("No bill failed")

topups = 0
while balance < 300:
    balance += 100
    topups += 1
    print("Top-up", topups, "balance", balance)
    if topups == 2:
        print("Top-up limit reached")
        break
else:
    print("Balance restored")

if balance >= 300:
    status = "healthy"
elif balance >= 100:
    status = "low"
else:
    status = "empty"
print("Status:", status)

Press Play to run the program line by line, or step with ← →.

00/21

Variables

Nothing defined yet.

Output

Nothing printed yet.

What to notice

  1. The first True branch wins. In an if / elif / else chain, Python stops testing at the first condition that holds. Order the tests from most specific to least specific.
  2. for gives you items, not positions. for amount in bills hands you 120, then 250, then 90. If you also need the position, use enumerate(bills).
  3. continue skips a round; break ends the loop. The OTP bill is skipped with continue and the loop carries on. The unaffordable bill triggers break and the loop is over.
  4. A loop’s else means “no break happened”. It runs after a for finishes its items or a while finds its condition False, even if the body never ran (see the 1000 scenario). It does not run after a break.
  5. A while loop needs an exit. balance += 100 moves the condition towards False, and the topups == 2 check is a safety cap. Without one or the other, the loop would never end.

Why this matters for AI work

The core of every agent framework is a while loop: call the model, run the tool it asked for, call the model again, until the reply has no tool call, then break. Tool code is mostly if: validate the arguments, return an error dict when they are wrong. And a test suite is a for over cases with an if that checks each result. The lesson on the agent loop shows the first of these in action.

Check your understanding

1. A for loop has an else block, and the loop exits through break. Does the else run?
2. What is the difference between continue and break?
3. balance is 390. In the chain if balance >= 300 ... elif balance >= 100 ... else, which blocks run?