01.03 Lesson 3 of 10
36 minDecisions & 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/elsebranches. - Loop over a sequence or range.
- Use
enumerate,zip,breakandcontinueappropriately.
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
ExerciseSummarize hourly demand
Use a small list of hourly counts to calculate a total, skip missing entries and identify peak-hour candidates.
- Loop through
[12, 18, None, 25, 19]. - Skip
Nonevalues withcontinue. - Track the running total and number of valid values.
- Print the average and every value above 18.
The missing value is excluded from both the sum and the denominator.
Free references
Study resources
- 01
- 02
Check your understanding
Self-test
-
Question 1
When should you use
enumerate(items)?When you need both each item and its zero-based position. -
Question 2
What does
continuedo inside a loop?It skips the rest of the current iteration and moves to the next item.
Completion check
Move on when
You can process a list, skip invalid entries and compute a summary with a clear loop.