hayaliv

hayaliv / Hi! Python / Level 0

Control flow

if chooses a path, for and while repeat work, and break and continue steer a loop.

Hi! Python · Level 0: Python core · Checked against the Python 3.12 documentation · Updated 2026-10-17

Think of it like this

Think of a post office sorting table. A clerk checks each letter in turn (for), puts it in one bin depending on its address (if/elif/else), and may stop early when a stop-sign letter arrives (break).

Where the analogy stops being true. A clerk uses judgement, but Python follows your conditions exactly and checks them in order.

What to know

Example

replies = ["Let's meet", "Not interested", "Send pricing"]
for i, r in enumerate(replies, start=1):
    print(i, r)
counts = {"meeting_request": 3, "not_interested": 5, "question": 0}
for label, n in counts.items():
    if n >= 5:
        print(label, "common")
    elif n > 0:
        print(label, "rare")
    else:
        print(label, "none")
total = 0
while total < 3:
    total += 1
print("total", total)
for n in range(5):
    if n == 1:
        continue
    if n == 3:
        break
    print(n)

It prints:

1 Let's meet
2 Not interested
3 Send pricing
meeting_request rare
not_interested common
question none
total 3
0
2

Predict, then check

1. What does this print?

print(list(range(3)))
Show the answer
[0, 1, 2]

range(3) produces 0, 1 and 2. The end point 3 is left out.

2. What does this print?

for n in range(5):
    if n == 2:
        continue
    if n == 4:
        break
    print(n)
Show the answer
0
1
3

n == 2 skips to the next round without printing. At n == 4 the loop stops before printing.

3. What does this print?

n = 0
while n < 3:
    n += 2
print(n)
Show the answer
4

n goes 0, then 2, then 4. At 4 the condition n < 3 is false, so the loop ends and 4 is printed.

4. What does this print?

x = 0
if x > 5:
    print("big")
elif x > 3:
    print("mid")
print("done")
Show the answer
done

Neither condition is true and there is no else, so no block runs. Only the last line prints.

Try it

Write first_meeting(labels) that returns the index of the first 'meeting_request' in the list, or -1 if there is none. Use a loop.

def first_meeting(labels):
    return -1
Show a solution
def first_meeting(labels):
    for i, label in enumerate(labels):
        if label == 'meeting_request':
            return i
    return -1

Common mistake

range(3) never yields 3. Its end point is not part of the sequence.

In a small-language-model project

In a fine-tuning project you usually loop over examples with enumerate to number them, and over a counts dict with items() to print a label report.

Sources

Each quote below appears word for word on the cited page of the official Python documentation (version 3.12).

Step through this lesson in the Hi! Python desktop

← Lists, tuples, dicts and setsFunctions →