Bootcamp Curriculum • 5 Modules • 12 Chapters • Multi-Language Runner (Python, JS, Java, C++) • Interactive Memory Trace • AI Mentor
CHAPTER 07 · LOOPS6 min read

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.

By the end of this chapter, you can:
  • 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.
Explanation DepthTailor the level of detail to your learning goal
💻 Standard College Notes

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.

💡range(1, 10) produces numbers from 1 up to 9; stop is always exclusive.

Accumulator pattern: Calculating the sum of numbers

An accumulator variable starts at 0. Inside the loop, each item is added to the running total.

example_1.py
Ctrl + ↵ to run
Terminal Output
Ready to execute
Click "▶ Run Code" or press Ctrl+Enter to compile & run this snippet.

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.

example_2.py
Ctrl + ↵ to run
Terminal Output
Ready to execute
Click "▶ Run Code" or press Ctrl+Enter to compile & run this snippet.
✦ Interactive Dry-Run Visualizer

Interactive Dry-Run Table: High-Score Tracker in Memory

Watch highest_score update whenever a larger value is encountered in the loop.

STEP1 / 6
1scores = [65, 91, 86]👉 Executing
2max_val = 0
3for s in scores:
4 if s > max_val:
5 max_val = s
6print(max_val)
VariableValue in MemoryData Type
scores[65, 91, 86]list of int
Initialize score list

3 items in sequence.

Console Stream (stdout)
(No output generated yet)
Line 1: 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.

⚡ +100 XP
fix_bug.pyPython 3.10
⚡ Quick Revision Quiz

Predict The Output (2 Questions)

Question 1 of 2:
What numbers are generated by range(2, 8, 2)?
Question 2 of 2:
What happens if you modify a list's length while iterating over it in a for loop?

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!