The magic of for loops & range()
Why write the same instruction twenty times when you can write it once? A for loop visits every item in a sequence, providing a fundamental tool for data processing and animation.
- Follow how a for loop iterates through sequences.
- Use range(start, stop, step) to repeat actions precisely.
- Calculate totals with an accumulator and find maximum values.
for ... in loops, range() sequences, and accumulator variables.
Syntax: for item in iterable:. Use range(start, stop, step) for counting loops. Accumulator variables sum or aggregate results across loop iterations.
Accumulator pattern: Calculating the sum of numbers
An accumulator variable starts at 0. Inside the loop, each item is added to the running total.
High-Score Finder algorithm (without max())
How does the computer find the highest number? Compare each candidate against the current highest and update when a larger number is found.
Interactive Dry-Run Table: High-Score Tracker in Memory
Watch highest_score update whenever a larger value is encountered in the loop.
| Variable | Value in Memory | Data Type |
|---|---|---|
| scores | [65, 91, 86] | list of int |
3 items in sequence.
scores = [65, 91, 86]🔧 Range Off-By-One Bug in Accumulator
A loop meant to sum numbers from 1 to 10 stopped at 9 due to range stop exclusivity.
Predict The Output (2 Questions)
Your lightbulb moment
The key takeaway
For loops iterate through sequences one item at a time. Combine them with accumulators and conditions to solve real algorithmic problems.
Make it yours
Try changing the list of scores to include 100 to watch the algorithm recognize the new high score.
Try editing the code in the playground above in Python, JavaScript, Java, or C++, and use the step-by-step Dry-Run Table to inspect how variables mutate in memory. If you get stuck, click the 🤖 AI Doubt Solver button on your screen for instant explanations!