Skip to content
devtoolbox.cc

Python · Chapter 3 of 21

Python if, elif, else and loops: for, while, range and break

15 min study · Examples checked with Python 3.14 and 3.15 ·

A script that runs every line once, top to bottom, can only do one thing. Real programs choose between paths and repeat work until a job is done. This chapter covers the two tools for that: conditions with if, and loops with for and while. Along the way it shows the edge cases (empty input, no match, a valid zero) where control flow usually goes wrong.

Comparisons and truth values

A comparison produces True or False. Python lets you chain comparisons the way you would write them on paper, and combine conditions with and, or and not:

minutes = 45
is_enrolled = True

print(30 <= minutes < 60)             # True
print(is_enrolled and minutes > 0)    # True
print(not is_enrolled or minutes == 0)  # False

30 <= minutes < 60 means 30 <= minutes and minutes < 60, with minutes evaluated once.

Any object can stand in for a condition. The values that count as false are False, None, zero of any numeric type, and empty containers: "", [], {}, (), set(). Everything else counts as true. That is why if lessons: is the usual way to ask “is this list non-empty?”.

Two operators look alike but ask different questions. == compares values; is asks whether two names point at the very same object. Use is for None (if mentor is None:) and == for numbers and strings. is can appear to work on small numbers because the interpreter reuses some objects, and then fail on larger ones.

and, or and defaults

and and or stop evaluating as soon as the answer is known, and they return one of their operands rather than a plain boolean. That makes or a compact way to supply a default:

nickname = ""
print(nickname or "Guest")         # Guest

lessons = []
if lessons and lessons[0] == "Intro":
    print("Starts with the intro")  # skipped: lessons[0] is never evaluated

page_size = 0
print(page_size or 20)                          # 20 (wrong if 0 was meant)
print(20 if page_size is None else page_size)   # 0

The second example relies on short-circuiting: with an empty list, lessons[0] would raise an IndexError, but and never gets that far. The last two lines show the trap with or: it replaces every false value, including a legitimate 0. When zero or an empty string is a valid input, test for None explicitly.

Choose one branch with if, elif and else

An if statement checks its conditions in order and runs the first block whose condition is true. The rest are skipped.

score = 84

if score >= 90:
    level = "excellent"
elif score >= 75:
    level = "good"
elif score >= 50:
    level = "pass"
else:
    level = "retry"

print(level)  # good

Order matters: if the >= 50 test came first, a score of 95 would stop there. Use elif when the cases exclude each other, and separate if statements when several actions can apply at once. A block cannot be empty, so use pass as a placeholder while you write the rest.

For a choice between two values, the conditional expression fits on one line: label = "pass" if score >= 50 else "retry". Keep it for short choices; anything with several steps reads better as a full statement. Deeply nested if blocks are a sign that a function with early return statements would be clearer (chapter 7).

Loop over data with for

A for loop takes the items of an iterable, one at a time: a list, a string, a range, a file, a dictionary. There is no index to manage unless you ask for one.

scores = [84, 52, 91, 75]
passed = 0
for score in scores:
    if score >= 60:
        passed += 1
print(passed)  # 3

for number, score in enumerate(scores, start=1):
    print(f"Attempt {number}: {score}")

print(any(s > 90 for s in scores), all(s > 50 for s in scores))  # True True

enumerate hands you the position and the item together, which is clearer than keeping a counter. any and all answer “does at least one item match?” and “do all items match?” without an explicit loop; both stop early, as soon as the answer is known.

range produces a sequence of integers. range(stop) starts at 0 and stops before stop; range(start, stop, step) sets all three.

print(list(range(4)))          # [0, 1, 2, 3]
print(list(range(1, 10, 3)))   # [1, 4, 7]
print(list(range(5, 0, -1)))   # [5, 4, 3, 2, 1]
print(list(range(5, 0)))       # []
print(len(range(0, 1_000_000_000, 2)))  # 500000000

The end value is excluded, so range(1, 10) stops at 9. A step that points away from the stop value gives an empty range, and a step of zero is an error. A range does not build a list of all its numbers: it computes them on demand, which is why the last line is instant. Call list() on it only when you need the numbers stored. Loops can also be nested, in which case the inner loop runs completely for every pass of the outer one.

Repeat while a condition holds

Use while when you don’t know in advance how many passes are needed, only when to stop:

balance = 100
weeks = 0
while balance < 150:
    balance *= 1.1
    weeks += 1
print(weeks, round(balance, 2))  # 5 161.05

Something inside the loop must eventually make the condition false, or it runs forever. Interactive programs often loop with while True and leave with break:

while True:
    topic = input("Topic (or 'quit'): ").strip()
    if topic.casefold() == "quit":
        break
    if not topic:
        continue
    print(f"Added {topic}")

break leaves the innermost loop immediately. continue skips the rest of the current pass and starts the next one. Both are fine in small loops; if a loop needs several of them, consider moving its body into a function.

The assignment expression := (often called the walrus operator) assigns and tests in one step. It shortens loops that read until a sentinel value appears:

pending = ["intro", "variables", "", "loops"]
while (topic := pending.pop(0)):
    print("Studying", topic)
print("Stopped at the blank entry")

The loop pops items until it gets an empty string, which is false. Use := when it removes real duplication; in most code a plain assignment on its own line is easier to read.

Search with break and loop else

Loops accept an else block, which runs only if the loop finished without hitting break. That fits searches: break means “found”, else means “looked everywhere”.

lessons = ["Variables", "Loops", "Functions"]
wanted = "Classes"

for lesson in lessons:
    if lesson == wanted:
        print("Found", lesson)
        break
else:
    print(wanted, "is not in the course")  # Classes is not in the course

The else also runs for an empty list, since nothing could break. For a plain yes/no question, wanted in lessons is shorter; the loop form earns its place when you need to do something with the match.

One rule for every loop: don’t add or remove items of a list while you are iterating over it. Removing shifts the remaining items down, and the loop skips one. Build a new list instead, for example [s for s in scores if s >= 0] (chapter 4), or loop over a copy with for s in scores[:].

Practice

Given scores = [84, -1, 52, 101, None, 91, 75], process the values in order: stop at None, skip anything outside 0 to 100, and count the passes (60 or more). Then, separately, find the first valid score above 90 in the whole list, or print a message if there is none.

Answer check: the first loop sees 84, -1, 52 and 101 before stopping at None; only 84 and 52 are valid, so one pass is counted. The search, which must skip None explicitly (comparing None > 90 raises a TypeError), finds 91. Try the search on an empty list and confirm that the loop’s else runs.

Summary

Comparisons chain, and every object has a truth value, with empty and zero values counting as false. or is a handy default, except when zero or an empty string is valid. if/elif picks the first match, for walks an iterable, while follows changing state, and break with loop else expresses “found” versus “not found”. Always try the empty case.

All Python chapters