Python 101Free
CONTROL FLOW

Loops

Doing things repeatedly with for and while.

SECTION 01

for over an iterable

Python's for loop is not a counter loop. It walks over an iterable, binding each item to the loop variable in turn. The iterable can be a list, a string, a dict, a file object, a range, or any object that defines an iterator.

range(start, stop, step) is the closest thing to the C-style counter. It produces an iterator that yields integers in the requested range. For most purposes you write for i in range(n): and read it as "do this n times".

If you find yourself reaching for an index just to read both the index and the value, use enumerate(items). It yields (i, item) pairs and is more idiomatic than tracking an integer manually.

python
for i in range(3):
    print(i)             # 0, 1, 2

for i, name in enumerate(["a", "b"]):
    print(i, name)       # 0 a, then 1 b
SECTION 02

while and conditions

Use while when you do not know up front how many iterations you need. The condition is checked at the top of each pass. As soon as it evaluates to false, the loop ends and execution continues after the body.

The loop variable is yours to manage. Forgetting to update it is the easiest way to get an infinite loop. If your while body never decreases or invalidates whatever the condition tests, the loop will run forever.

A common pattern is while True: paired with a break somewhere in the body. This reads as "keep going until we explicitly decide to stop". Use it when the exit condition is hard to express in the loop header itself.

python
while True:
    line = input("> ")
    if line == "quit":
        break
    handle(line)
SECTION 03

break, continue, for-else

break exits the innermost enclosing loop immediately. continue skips the rest of the current iteration and jumps back to the top of the loop, picking up the next item. Both are tools to escape the structure of a loop without restructuring the surrounding code.

Less familiar is the else clause on a loop. for x in items: ... else: ... runs the else block only if the loop completed without hitting a break. It is the cleanest way to express "did we finish without finding what we were looking for?".

Most code uses break and continue regularly and for-else once or twice. The for-else version is worth knowing because the alternative is an extra flag variable that adds noise.

python
for x in items:
    if x == target:
        print("found")
        break
else:
    print("not found")   # only runs if no break happened
← PREVIOUS
Conditionals
NEXT →
Exceptions