23
Loops
Loops: Let the Program Handle the Repetition
What You Might Be Wondering
"Can't I just copy-paste a few lines to get the same result?"
Sure, for tiny scripts. But in real projects, copy-paste spirals out of control fast. A loop applies the same rule to a batch of data — that's its entire purpose.
One-Line Definition
Loops repeat code execution based on a condition or a sequence.
Real-Life Analogy
An assembly line: as long as there are items to process, the station keeps doing the same operation.
Minimal Working Example
for i in range(1, 6):
print(i)
for vs while
# for: when you know what you're iterating over
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# while: condition-driven
count = 3
while count > 0:
print(count)
count -= 1
break and continue
for n in range(1, 8):
if n == 3:
continue
if n == 6:
break
print(n)
Quick Quiz (5 min)
- Print all multiples of 3 from 1 to 100.
- Use
whileto calculate the sum from 1 to n. - Allow max 3 password attempts, exit early on success.
Quiz Rubric & Grading Criteria
- Direction: write runnable code that covers the core requirements and edge cases from the prompt.
- Criterion 1 (Correctness): main flow produces correct results, key branches execute.
- Criterion 2 (Readability): clear variable names, no excessive nesting.
- Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.
Take-Home Task
Build an "order counter":
- Input: a list of order amounts
- Loop to calculate the total
- Count how many orders are over 100
Acceptance Criteria
You can independently:
- Choose between
forandwhilebased on the situation - Use
break/continuecorrectly - Avoid infinite loops
Common Errors & Debugging Steps (Beginner Edition)
- Error message looks like gibberish: read the last line for the error type (
TypeError,NameError, etc.), then trace back to the offending line. - Not sure what a variable holds: drop a temporary
print(variable, type(variable))to check. - Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.
Common Misconceptions
-
Misconception: forgetting to update the state variable inside
while. -
Reality: every iteration must advance the condition. Otherwise you've got an infinite loop.
-
Misconception: stuffing heavy logic inside the loop body.
-
Reality: keep loops for orchestration. Extract complex processing into functions.