Python

Control flow — if/else and loops

How to make a program actually make decisions and repeat itself — the two mechanisms almost every piece of real code is built out of.

Beginner

3 min read

if — running code only when something's true

age = 20
 
if age >= 18:
    print("You can vote")
else:
    print("Too young to vote")

if CONDITION: runs the indented block underneath it only when CONDITION evaluates to True; else: runs its block otherwise. Indentation isn't a style choice in Python — it's how the language knows which lines belong inside the if block. Four spaces per level is the near-universal convention; mixing tabs and spaces, or indenting inconsistently, causes an IndentationError.

score = 75
 
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

elif ("else if") chains additional conditions — Python checks them top to bottom and runs the first one that's True, skipping the rest entirely, even if a later condition would also have matched.

Comparison and boolean operators

5 == 5      # True  — equal to
5 != 3      # True  — not equal to
5 > 3       # True  — greater than
5 >= 5      # True  — greater than or equal to
 
age = 20
has_id = True
age >= 18 and has_id     # True — both must be true
age >= 18 or has_id      # True — at least one must be true
not has_id                # False — flips True/False

A very common beginner mistake: = assigns a value, == checks equality — if x = 5: is a syntax error in Python specifically to prevent accidentally writing that instead of if x == 5:.

for loops — doing something to each item in a sequence

fruits = ["apple", "banana", "cherry"]
 
for fruit in fruits:
    print(fruit)
apple
banana
cherry

for VARIABLE in SEQUENCE: runs the indented block once for every item in SEQUENCE, with VARIABLE bound to the current item each time. This is the standard way to process every element of a list, every character of a string, or every line of a file — anywhere the shape is "do this to each thing in a collection."

for i in range(5):
    print(i)
0
1
2
3
4

range(5) produces the numbers 0 through 4 (five numbers, starting at 0, not including 5) — the standard way to run a loop body a fixed number of times, or to get a numeric index alongside each item (for i in range(len(fruits)):).

while loops — repeating until a condition becomes false

count = 0
while count < 3:
    print(count)
    count += 1   # shorthand for count = count + 1
0
1
2

while CONDITION: keeps running its block as long as CONDITION stays True, checking it again before every repetition. Forgetting to update whatever the condition depends on (count += 1 here) produces an infinite loop — the single most common while-loop bug, worth double-checking every time.

break and continue — changing a loop's flow from inside

for n in range(10):
    if n == 5:
        break        # exit the loop immediately, skip everything after
    print(n)
for n in range(5):
    if n == 2:
        continue     # skip just this iteration, move to the next one
    print(n)

break stops the loop entirely, right where it is. continue skips only the rest of the current iteration and moves on to the next one — the loop itself keeps going. Both are most useful for "stop/skip once some condition is met" logic that would otherwise need an extra if/flag variable wrapped around the whole loop body.

Further reading

Check your understanding

A quick comprehension check — not tracked, not graded, just for you.

1. How many numbers does `range(5)` actually produce?

2. In an if/elif/elif/else chain, what happens once Python finds a branch whose condition is True?

3. What's the most common cause of an infinite `while` loop?

4. What's the difference between `break` and `continue` inside a loop?