Python

Python Loops and Conditionals — for, while, if, range, and enumerate

Most programs spend their time on two moves. A conditional picks which branch runs, and a loop runs a block more than once. This guide works through both moves in small programs: an if chain that grades a score, a for loop over a list and over a range, a while loop with a counter, the break and continue statements that change a loop from inside, the else clause that a loop runs when it finishes without a break, and the enumerate and zip helpers that pair a position or a second list with each item.

Written November 12, 2026 · Tested with Python 3.12.3 · 9 min read

By the end of this guide
  • The main program: an if chain, a for loop, and range
  • While loops, break, and continue
  • Positions and pairs: enumerate and zip
  • The else clause on a loop

Written November 12, 2026

Tested with Python 3.12.3

What this guide is

A conditional is a test with branches. The program checks a condition, runs one block when the condition holds, and runs a different block when it does not. A loop is a block with a repeat rule. A for loop repeats once for each item in a sequence, and a while loop repeats while a condition stays true. Between them, the two forms cover the bulk of daily control flow: grading a value, adding up a list, counting with a range, stopping early when a search succeeds, and skipping items that fail a test. The sections below take the forms in order, and each program is complete, so each one can be typed in and run as it stands.

The main program: an if chain, a for loop, and range

Python
score = 74
if score >= 90:
    print("A")
elif score >= 70:
    print("B")
elif score >= 50:
    print("C")
else:
    print("F")
total = 0
for n in [3, 1, 4]:
    total += n
print("total", total)
for i in range(3):
    print("i", i)
print(list(range(1, 10, 3)))
print(list(range(5, 0, -1)))

The exact output:

Output
B
total 8
i 0
i 1
i 2
[1, 4, 7]
[5, 4, 3, 2, 1]

The if chain tests its conditions from the top. A score of 74 fails the first test, passes the second, and prints B. The later tests never run, because one branch of a chain is the whole result: the first true condition wins, and else runs only when every condition fails. Order matters for that reason. A chain that tests the wide condition first makes the narrow branches below it dead code, so chains go from the narrowest test to the widest, or from the highest band to the lowest, as this one does.

The for loop below the chain walks the list in order and adds each item to a running total, which ends at 8. A for loop needs no counter and no end test of its own. It takes the next item on each pass and stops when the sequence runs out. The range calls show the counting form. Range with one number counts from 0 up to, but not including, that number. Range with a start, a stop, and a step counts by that step, and a negative step counts down, again stopping before the final bound.

While loops, break, and continue

A while loop repeats while its condition stays true, so the block itself must change something that the condition reads. A counter that grows toward the bound is the plain form:

Python
n = 0
while n < 3:
    print("n", n)
    n += 1
print("done", n)
for n in range(6):
    if n == 2:
        continue
    if n == 5:
        break
    print("seen", n)
print("after loop")

The exact output:

Output
n 0
n 1
n 2
done 3
seen 0
seen 1
seen 3
seen 4
after loop

The counter prints 0, 1, and 2 inside the loop. On the pass where the counter reaches 3 the condition fails, the loop ends, and the line after the loop runs with the counter at 3. Drop the line that raises the counter and the condition never fails, so the loop never ends. That is the standing risk of the while form, and the reason a for loop is the better default when a sequence or a count is known in advance.

The second loop shows the two statements that steer a loop from inside. Continue skips the rest of the current pass and starts the next one, so the pass for 2 prints nothing. Break leaves the loop at once, so the pass for 5 prints nothing and no later pass runs at all. The line after the loop runs in both cases, which is what makes break the right tool for a search that can stop early: find the item, break, and carry on with the code below.

Positions and pairs: enumerate and zip

A plain for loop hands over items, not positions. When a line of output needs the position as well, enumerate wraps the sequence and hands over a pair on each pass, a number and the item at that number. The start keyword moves the first number, which suits output meant for people, where lists start at 1. When two lists belong together, zip walks them side by side and stops at the shorter one:

Python
names = ["ana", "bo", "cy"]
scores = [10, 20, 30]
for i, name in enumerate(names):
    print(i, name)
for i, name in enumerate(names, start=1):
    print(i, name)
for name, score in zip(names, scores):
    print(name, score)
print(list(zip(names, scores)))

The exact output:

Output
0 ana
1 bo
2 cy
1 ana
2 bo
3 cy
ana 10
bo 20
cy 30
[('ana', 10), ('bo', 20), ('cy', 30)]

The pairs that enumerate and zip hand over are tuples, and the loop line unpacks each tuple into two names at once. That is why the last line, which builds a list from zip without unpacking, shows the pairs in brackets. Zip stopping at the shorter list is a quiet trap: two lists of different lengths pair up with no error, and the extra items at the end of the longer list are simply never seen. Code that needs the lengths to match has to check them itself before the loop.

The else clause on a loop

A loop can carry an else clause, and that clause runs when the loop ends without a break. A for loop that runs out of items ends that way, and so does a while loop whose condition turns false. A loop stopped by break skips its else clause. The pair of forms makes a search read in one piece: the break says the item turned up, and the else says it did not:

Python
for n in [3, 7, 4]:
    if n == 7:
        print("found 7")
        break
else:
    print("not found")
for n in [3, 1, 4]:
    if n == 7:
        print("found 7")
        break
else:
    print("not found")
n = 0
while n < 10:
    n += 2
    if n > 4:
        break
else:
    print("while finished")
print("while stopped at", n)

The exact output:

Output
found 7
not found
while stopped at 6

The first search finds 7 and breaks, so its else clause stays silent. The second search runs out of items, so its else clause prints the not found line. The while loop at the end breaks when its counter passes 4, at the value 6, so its else clause stays silent too, and the final line reports where the counter stopped. The shape replaces a flag variable in a search: without the loop else, the same code sets a found flag before the break and tests it after the loop, which is more state to keep straight.

Comprehensions: a loop in one line

A list comprehension is a for loop written inside brackets. It builds a list from a sequence, with an optional test that keeps only some items. The same loop in statement form takes four lines: an empty list, a for line, a body line, and the list at the end. The one-line form is the form Python code uses for short maps and filters, because the whole build sits in one place:

Python
print([n * n for n in range(5)])
print([n for n in range(10) if n % 2 == 0])
words = ["a", "veldica", "go", "python"]
print([w.upper() for w in words if len(w) > 2])
total = sum(n for n in range(5))
print("sum", total)
d = {n: n * n for n in range(4)}
print(d)

The exact output:

Config
[0, 1, 4, 9, 16]
[0, 2, 4, 6, 8]
['VELDICA', 'PYTHON']
sum 10
{0: 0, 1: 1, 2: 4, 3: 9}

The first line squares each number the range hands over. The second keeps only the even numbers, where the test is the remainder check: a number divided by 2 with remainder 0 is even. The third line shows a method call inside the build, keeping the words longer than two letters and putting them in upper case. The sum line is a generator form, the same shape in round brackets, which hands values to sum one at a time without building a list first. The last line is a dict comprehension, building a dict from pairs, with the key before the colon and the value after it. A comprehension with two tests, a nested loop, or a side effect stops being short, and at that point the statement form is the clearer one to write and to read.

Nested loops and pass

A loop inside a loop runs its full set of passes for each pass of the outer loop. Two ranges of two and three make six inner passes, and the pair of counters names each one. The pass statement at the end of this section is the other small form worth knowing: it does nothing, and it exists so a block that Python requires can stand empty while its real body is still unwritten:

Python
for row in range(2):
    for col in range(3):
        print(row, col, end="; ")
    print()
x = 0
while True:
    x += 3
    if x >= 7:
        break
print("x", x)
for ch in "abc":
    pass
print("pass leaves the loop finished")

The exact output:

Output
0 0; 0 1; 0 2; 
1 0; 1 1; 1 2; 
x 9
pass leaves the loop finished

The print call with end set to a short string keeps each inner pass on one line, and the bare print after the inner loop ends the line. The while loop in the middle is the deliberate endless form: its condition is the constant True, so only the break inside can end it, and the counter steps by 3 until it reaches 9. That form is common for work that waits on input or on a network, where the stop rule sits in the middle of the block rather than at the top. It is safe only when the break is sure to fire, so the stop test belongs near the top of the block, before any line that might skip it.

Which form for which job

Job Form Why
Pick one branch from a set of bands An if, elif, else chain The first true test wins, and else covers the rest
Walk every item in a list or a string A for loop over the sequence It takes each item in order and stops at the end on its own
Repeat a block a fixed number of times A for loop over range Range counts from 0 up to, but not including, its bound
Count down, or count by a step Range with a step A step of 3 counts by threes, and a negative step counts down
Repeat while a rule holds A while loop The test sits at the top and is checked before each pass
Leave a loop as soon as a search succeeds Break It ends the loop at once and runs the code below it
Skip one item and keep going Continue It ends the current pass and starts the next one
Report that a search found nothing An else clause on the loop It runs when the loop ends without a break
Walk items with their positions Enumerate It hands over a number and an item on each pass
Walk two lists side by side Zip It pairs items in order and stops at the shorter list
Build a list with a short map or filter A comprehension The whole build sits in one line inside brackets

Checklist

  • Before writing an if chain, order the tests so the first true one is the branch you want; later tests never run after a match.
  • Before walking a sequence with a counter and an index, switch to a plain for loop, and add enumerate only when the position is part of the output.
  • Before writing a while loop, name the line inside the block that changes the condition; a block with no such line never ends.
  • Before using range, remember its stop is left out, so range(3) gives 0, 1, and 2, not 3.
  • Before pairing two lists with zip, check their lengths when a mismatch would hide data, because zip stops at the shorter list in silence.
  • Before setting a found flag around a search loop, use the loop else clause instead, and let break carry the found case.
  • Before stretching a comprehension past one test or one loop, write the statement form; long comprehensions are hard to read and hard to debug.

Sources

Keep Exploring