7 stages2 sections22 units

01.03 Lesson 3 of 10

36 min

Decisions & Loops

Use conditions and iteration to process collections without writing repetitive code.

By the end of this lesson

You will be able to

  • Write if / elif / else branches.
  • Loop over a sequence or range.
  • Use enumerate, zip, break and continue appropriately.

Branch on a condition

A conditional chooses which block runs. Prefer conditions that describe the business rule directly, and avoid deeply nested branches when an early continue makes the loop clearer.

hour = 8

if hour < 6:
    period = "early"
elif hour < 12:
    period = "morning"
else:
    period = "later"

Iterate over values first

A for loop visits each item in an iterable. Use enumerate when you also need the position, and zip when two sequences should be processed together. Avoid changing the collection you are currently iterating over.

hours = [6, 7, 8, 9]
for position, hour in enumerate(hours):
    print(position, hour)

labels = ["Mon", "Tue", "Wed"]
counts = [12, 18, 15]
for label, count in zip(labels, counts):
    print(label, count)

Apply what you learned

Exercise

Summarize hourly demand

Use a small list of hourly counts to calculate a total, skip missing entries and identify peak-hour candidates.

  1. Loop through [12, 18, None, 25, 19].
  2. Skip None values with continue.
  3. Track the running total and number of valid values.
  4. Print the average and every value above 18.
Done when

The missing value is excluded from both the sum and the denominator.

Free references

Study resources

2 links
  1. 01
    More control flow tools Article

    Read the if, for, range, break and continue sections.

  2. 02
    Loops and Iterations Video

    Watch this one video for a visual walkthrough of for and while loops.

Check your understanding

Self-test

2 questions
  1. Question 1

    When should you use enumerate(items)?

  2. Question 2

    What does continue do inside a loop?

Completion check

Move on when

You can process a list, skip invalid entries and compute a summary with a clear loop.

Quick find

Search Michi

Type to search every stage, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels