PYTHON / CHAPTER 04
Decisions and repeating work
BeginnerChoose a branch and process a small list using indentation and a for loop.
By the end of this chapter
- Use a comparison in an if statement
- Recognize the role of indentation
- Accumulate a result across a for loop
The idea
A comparison such as points >= 3 evaluates to True or False. An if statement runs its indented block only when the condition is true. An optional else block handles the other case. The colon begins a block, and consistent indentation shows which statements belong to it.
A for loop visits the values in a sequence. In for points in scores:, points receives one value on each repetition. A variable initialized before the loop can accumulate a result. Initialize passed = 0 once, then increase it only when the current score meets the requirement.
Trace the program with a tiny list. For [2, 5, 3], ask the same question three times: is this score at least three? The answers are false, true, and true, so the final count is two. Keep the final print outside the loop when you want one result after all values have been checked.
scores = [2, 5, 3]
passed = 0
for points in scores:
if points >= 3:
passed = passed + 1
print(passed)2
Only 5 and 3 satisfy the condition. The counter is initialized before the loop and printed after the loop finishes.
Try it yourself
Count values greater than zero in [0, -2, 4, 1]. Predict the result, then test an empty list.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open Python coding challengesCHECK YOUR UNDERSTANDING