COMPUTER PROGRAMMING 1 (PYTHON) • CONTROL FLOW

For Loops — I can write for loops over range and over collections and trace iterations at my level.

Master the art of repeating actions automatically using Python's powerful for loop.

Historical Context & Motivation

Imagine you need to print "Hello" one thousand times. Without a loop, you would have to write one thousand print statements — tedious, error-prone, and practically impossible to maintain. The for loop was invented precisely to solve this problem: it tells the computer to repeat a block of code a specific number of times, or once for each item in a collection. This concept of iteration — the controlled repetition of instructions — is one of the most fundamental ideas in all of computer science.

The need for repetition in computation goes back to the very dawn of programming. Early computers were programmed by physically rewiring circuits, and any repeating task required the operator to reset the machine manually. As programming languages evolved, designers realized that loops were essential to making computers truly powerful. Let's trace that evolution.

1843
Ada Lovelace's Algorithm
Ada Lovelace wrote the first published algorithm for Charles Babbage's Analytical Engine. Her notes described a process that looped back on itself to compute Bernoulli numbers — the earliest recorded use of iteration in computing.
1957
FORTRAN's DO Loop
FORTRAN, one of the first high-level programming languages, introduced the DO loop. This allowed programmers to specify a variable, a start value, and an end value — the ancestor of today's counted loops.
1972
C Language for Loop
The C programming language formalized the three-part for(init; condition; update) syntax. This pattern influenced dozens of languages including Java, JavaScript, and C++.
1991
Python Is Born
Guido van Rossum released Python with a simplified for loop that iterates directly over collections. Instead of managing index variables manually, Python lets you loop over items naturally — a design philosophy centered on readability.
2000s+
For-Each Everywhere
Python's approach became so popular that many other languages adopted similar "for-each" loops. Java added its enhanced for loop in 2004, and JavaScript added for...of in 2015.

So how exactly does Python's for loop work? How do you tell it to count from 0 to 99, or to process every name in a list? And how can you trace what happens during each pass through the loop? These are the questions we'll answer in this lesson.

Core Principles & Definitions

Before we write any code, let's establish the foundational vocabulary and ideas that make for loops work. Every for loop, regardless of what it iterates over, relies on the same core principles.

1

Iteration

A single pass through the body of a loop. If a loop runs 5 times, it has 5 iterations. Each iteration executes the indented code block once.
2

Loop Variable

The variable that automatically takes on a new value at the start of each iteration. In for i in range(3), the loop variable is i, and it becomes 0, then 1, then 2.
3

Iterable

Any object Python can loop over item by item. Lists, strings, tuples, and the range() function all produce iterables. The loop pulls one element at a time from the iterable.
4

Loop Body

The indented block of code beneath the for statement. Everything inside this block runs once per iteration. In Python, indentation (typically 4 spaces) defines the body — no curly braces needed.
5

The range() Function

A built-in Python function that generates a sequence of integers. range(n) produces 0 through n−1. You can also specify a start, stop, and step: range(start, stop, step).

The basic syntax of a Python for loop is straightforward: for variable in iterable: followed by an indented body. The keyword for signals the start, in connects the loop variable to the iterable, and the colon : marks the end of the header line. Python then automatically assigns the next value from the iterable to the variable and executes the body until all values are exhausted.

✦ KEY TAKEAWAY
Think of a for loop like a playlist on your phone. The iterable is the playlist (the full list of songs). The loop variable is the "now playing" slot — it changes to the next song each time. The loop body is what you do with each song (listen, skip, add to favorites). When the playlist ends, the loop stops.

Visual Explanation — How a For Loop Flows

The diagram below shows the control flow of a for loop. Notice how the program checks whether more items remain in the iterable before each iteration. If items remain, the loop variable is updated and the body executes. When no items remain, execution continues with the code after the loop.

The diamond shape represents the decision point: does the iterable have another item? If yes, the loop variable updates and the body runs. The green arrow shows the loop cycling back. When the answer is no, execution exits to the code after the loop.

This flowchart applies to every for loop you'll ever write in Python, whether you're looping over a range() of numbers, a list of strings, or even the characters in a single word. The mechanism is always the same: pull the next item, run the body, check again.

How range() and Collection Iteration Work

The range() Function in Detail

The range() function generates a sequence of integers. It has three forms, each adding more control over the generated sequence. Understanding these forms is crucial because range() is the most common way to run a for loop a specific number of times.

RANGE WITH ONE ARGUMENT
range(stop) → 0, 1, 2, …, stop − 1
stop — the exclusive upper bound (not included in the sequence). The sequence always starts at 0. Example: range(5) produces 0, 1, 2, 3, 4.
RANGE WITH TWO ARGUMENTS
range(start, stop) → start, start + 1, …, stop − 1
start — the inclusive starting value. stop — the exclusive upper bound. Example: range(2, 6) produces 2, 3, 4, 5.
RANGE WITH THREE ARGUMENTS
range(start, stop, step) → start, start + step, start + 2×step, …
step — the increment between values. Can be negative for counting down. Example: range(0, 10, 2) produces 0, 2, 4, 6, 8. Example: range(10, 0, -2) produces 10, 8, 6, 4, 2.
⚠️ Common Pitfall
The stop value is never included in the sequence — it is exclusive. This is one of the most frequent beginner mistakes. If you want numbers 1 through 10, use range(1, 11), not range(1, 10).

Looping Over Collections

Python's for loop truly shines when iterating over collections like lists, strings, and tuples. Instead of using an index to access elements, Python hands you each element directly. For example, for name in ["Alice", "Bob", "Carol"]: assigns name the value "Alice" on the first iteration, "Bob" on the second, and "Carol" on the third. This is cleaner and less error-prone than managing an index counter yourself.

You can also loop over a string character by character. Writing for ch in "hello": gives you "h", then "e", then "l", and so on. Any object that is iterable — meaning it can produce items one at a time — works with Python's for loop.

Tracing Iterations Step by Step

One of the most important skills in programming is tracing — manually walking through your code line by line and recording the value of each variable at each step. Tracing a for loop means keeping track of the loop variable's value, the output produced, and any other variables that change inside the body. This skill helps you predict what your code will do before you even run it, and it is essential for debugging.

The trace table tracks the loop variable x and the computed expression x * 2 for each iteration. The output column shows what appears on screen after each pass.

When you trace a loop, draw a table with columns for each variable and the output. Add a new row for each iteration. This practice builds your mental model of how the computer executes your code. On quizzes and exams, trace tables are often required, so getting comfortable with them now will pay off significantly.

💡 Pro Tip
If your loop body updates an accumulator variable (like total = total + x), add a column for that variable too. Track its value before and after each iteration to catch off-by-one errors.

Worked Example — Summing a List

Let's work through a complete example that combines looping over a collection with an accumulator pattern. The goal is to compute the sum of all scores in a list.

Calculate the Total of a List of Scores
1
Step 1 — Define the DataStart with a list of test scores and an accumulator variable initialized to zero. scores = [85, 92, 78, 95, 88] total = 0
total = 0 (before loop begins)
2
Step 2 — Write the For LoopUse a for loop to iterate over each score. Inside the body, add the current score to total. for score in scores: total = total + score
The loop variable score takes each value from the list.
3
Step 3 — Trace Each IterationIteration 1: score = 85, total = 0 + 85 = 85 Iteration 2: score = 92, total = 85 + 92 = 177 Iteration 3: score = 78, total = 177 + 78 = 255 Iteration 4: score = 95, total = 255 + 95 = 350 Iteration 5: score = 88, total = 350 + 88 = 438
After all 5 iterations, total = 438
4
Step 4 — Output the ResultAfter the loop, print the result. print("Total:", total) This outputs: Total: 438
Final answer: 438
🔑 THE ACCUMULATOR PATTERN
The accumulator pattern is like a snowball rolling downhill. You start with a tiny snowball (total = 0), and each trip through the loop adds more snow to it. By the end, you've built up a big result from many small additions. This pattern works for summing, counting, building strings, and many other tasks.

range() Loops vs. Collection Loops — When to Use Each

Now that you know both styles of for loop, a natural question arises: when should you use for i in range(n) versus for item in collection? The table below compares the two approaches to help you choose the right one for each situation.

Comparing range-based and collection-based for loops in Python
Featurefor i in range()for item in collection
Best forRepeating an action a specific number of times, or when you need the indexProcessing each element in a list, string, or other collection
Loop variable holdsAn integer (the current count or index)The actual item from the collection (string, number, etc.)
Examplefor i in range(5): print(i)for name in names: print(name)
Pythonic?Yes, when counting is the goal. Avoid using range(len(list)) just to get items.Yes — this is the preferred Python style when you need each item directly.
RiskOff-by-one errors if you forget stop is exclusiveCannot easily access the index unless you use enumerate()
🧭 CHOOSING THE RIGHT LOOP
A good rule of thumb: if you need the items in a collection, loop over the collection directly. If you need the count or a numeric index, use range(). Avoid for i in range(len(my_list)) when for item in my_list does the job — simpler code has fewer bugs.

Connection to Advanced Concepts

The for loop you've learned today is the gateway to many powerful programming techniques. As you advance, you'll encounter nested loops (loops inside loops), while loops that repeat based on a condition rather than a collection, and list comprehensions that let you build new lists in a single line. The table below previews how today's concepts connect to what's ahead.

How today's for loop skills connect to future topics
Today's ConceptAdvanced ExtensionWhat's Different
for i in range(n)Nested loops: for i in range(n): for j in range(m)The inner loop runs completely for each iteration of the outer loop, creating n × m total iterations.
for item in collectionList comprehensions: [x*2 for x in nums]A compact one-line syntax to build a new list by transforming each item. Same logic, shorter code.
For loop (iterates over known items)While loop (iterates while a condition is true)While loops don't need a collection — they repeat as long as a Boolean condition remains True. Useful when you don't know how many iterations you need.
Tracing by handUsing a debugger (e.g., Python's pdb or VS Code debugger)Debuggers let you step through code line by line on screen, inspect variables, and set breakpoints — an automated version of tracing.

Don't worry about mastering these advanced topics right now. The important thing is that every one of them builds on the same fundamentals you're learning today: iterating over data, updating variables inside a loop body, and tracing what happens at each step. If you can do these three things confidently, you have a strong foundation for everything that comes next.

Practice Problems

Test your understanding with these five problems. They start with basic recall and build up to critical thinking. Try to answer each one on paper before reading the solution.

PROBLEM 1 — CONCEPTUAL
In the loop for color in ["red", "green", "blue"]:, how many iterations will occur? What is the value of color during the second iteration?
PROBLEM 2 — BASIC CALCULATION
What does range(2, 10, 3) produce? List all the values.
PROBLEM 3 — INTERMEDIATE
Trace the following code and determine the final value of count: count = 0 for letter in "banana": if letter == "a": count = count + 1 print(count)
PROBLEM 4 — APPLIED
A teacher stores quiz grades in a list: grades = [88, 76, 95, 63, 91, 84]. Write a for loop that prints only the grades that are 80 or above. Then, write a second loop that calculates the average of all grades.
PROBLEM 5 — CRITICAL THINKING
Consider the following two code snippets. Do they produce the same output? Explain your reasoning. Snippet A: words = ["cat", "dog", "bird"] for w in words: print(len(w)) Snippet B: words = ["cat", "dog", "bird"] for i in range(len(words)): print(len(words[i]))

Lesson Summary

A Python for loop repeats a block of code once for each item in an iterable. You can loop over a range() of integers when you need to repeat an action a specific number of times, or loop directly over a collection (like a list or string) to process each element. The loop variable automatically takes on the next value from the iterable at the start of each iteration.

The accumulator pattern (initializing a variable before the loop and updating it inside) lets you compute sums, counts, and other aggregated results. Tracing — building a table that tracks variable values across each iteration — is an essential debugging and exam skill. Remember: range(stop) starts at 0 and the stop value is always exclusive. When you only need items (not indices), loop over the collection directly — it's the Pythonic way.

Varsity Tutors • Computer Programming 1 (Python) • For Loops — I can write for loops over range and over collections and trace iterations at my level.