Not sure which lesson to do first? Find your level and get a plan →

CS Thinking · Programming Fundamentals · Grade 6-8

For Loop

A control structure that repeats a block of code a specific number of times or once for each item in a collection.


Quick Answer

A control structure that repeats a block of code a specific number of times or once for each item in a collection. Use it when you know before the loop starts what it should go through: the numbers 1 to 10, every name on a class list, each letter of a word. The loop variable takes each value in turn without you updating it, so it cannot stall the way a forgotten update stalls a while loop. In Python, range(5) gives 0, 1, 2, 3, 4: five values, starting at 0.

Why This Matters

For loops are how programs process whole collections: add up every score, send a message to every member, check every pixel in a photo. Because the loop variable steps forward by itself, the number of passes is guaranteed. Getting the range wrong is the classic slip: range(1, 10) stops at 9, so a times-table program meant to reach 10 × 7 quietly leaves out its last line.

Intuitive Explanation

A teacher handing back marked tests works through the stack: for each test, read the name, hand it over. The teacher never has to decide when to stop; the stack decides, by running out. A for loop works the same way. In for name in ['Ana', 'Ben', 'Cy']: print('Hi ' + name), name is 'Ana' on the first pass, 'Ben' on the second and 'Cy' on the third, and then the loop ends because the list has nothing left.

For counting, Python uses range. range(4) produces 0, 1, 2, 3: it starts at 0 and stops before 4, which gives exactly 4 values, and range(1, 6) gives 1 to 5. A running total shows the pattern: total = 0, then for i in range(1, 6): total = total + i. The total goes 1, 3, 6, 10, 15, so the loop adds the numbers 1 to 5 and finishes at 15.

A for loop needs its sequence before it starts. 'Keep rolling a die until you get a six' has no list to walk through, because nobody knows how many rolls it will take; that is a while loop's job. A second trap: removing items from a list while a for loop walks through it shifts the remaining items along, so some are skipped. Loop over a copy, or build a new list instead.

Think of it like this. Dealing cards around a table is a for loop: one card to each player, and the round ends when every player has one, with nobody counting aloud. The players are the collection and dealing a card is the body. The picture also predicts the classic bug: if a player leaves mid-round, as when you remove items while looping, someone gets skipped.

Core idea. For loops are best when you know how many times to repeat or when iterating over a collection. The loop variable takes each value automatically.


When to Use

Use a for loop when the work is for each item in a list, string or file, or a fixed number of times you can state before starting: 10 rounds, 7 days, every student. The loop variable then steps through the values by itself. If the number of repetitions depends on something that happens during the loop, such as a correct guess or a balance reaching a target, use a while loop. When the task needs each item's position as well as its value, loop over range(len(items)) or use enumerate.

Tip. Ask: Do you know before the loop starts exactly what it goes through: a fixed count, or every item of a list or string?

How to Recognize It

Look at what the repeating works through and whether that is fixed before the first pass.

  1. Is there a list, string or range whose items each need the same step?

    Yes means a for loop: for letter in word visits every letter once. If the steps carry on until something happens, such as a correct answer, use a While Loop.

  2. Is the number of repetitions a fixed number, even one stored in a variable such as n?

    Yes means for i in range(n) fits, and the loop variable updates itself. A count that is only discovered while the program runs points to a While Loop.

  3. Does the question ask how many times the body runs, or which values the loop variable takes?

    Yes means list the range carefully: range(2, 8) gives 2 up to 7, six values, because the stop number is never included.

  4. Does the loop need to stop early once a match is found?

    Yes means a for loop with break, or a while loop that tests for the match; a for loop with no break always visits every item.

For Loop vs While Loop vs Iteration

Every for loop can be rewritten as a while loop, so the choice can look like a matter of taste. What settles it is whether the list of things to go through exists before the first pass.

For Loop

Meaning
A for loop runs its body once per value in a range or once per item in a list, string or other collection.
Key test
What it visits is fixed before it starts; the loop variable updates itself.
Example
for ch in 'cat': print(ch) prints c, a and t, one per line.

While Loop

Meaning
A while loop repeats its body for as long as a condition stays true, checking before each pass.
Key test
The end depends on something that happens during the loop.
Example
while balance < 1000: balance = balance * 1.05 grows savings until they reach 1000 or more.

Iteration

Meaning
Iteration means repeating a set of steps, which is the idea behind both kinds of loop.
Key test
Describes repeating in general, before any loop is written.
Example
A plan saying 'check each answer on the quiz' is iteration; its code is usually a for loop.

Formula & Notation

Worked Examples

Example 1 — Total and average a list

Easy

scores = [8, 5, 9, 6]. The program runs total = 0, then for s in scores: total = total + s, then print(total / len(scores)). Trace the loop and give the printed value.
Show the steps and the answer
  1. Pass 1: s = 8, so total = 0 + 8 = 8.

    The loop variable takes the first item without any line like s = scores[0].

  2. Pass 2: s = 5, total = 13. Pass 3: s = 9, total = 22. Pass 4: s = 6, total = 28.

    Each pass moves s to the next item and adds it to the running total.

  3. There is no fifth item, so the loop ends after 4 passes.

    A for loop over a list runs once per item, so the list's length fixes the number of passes.

  4. Print 28 / 4 = 7.0.

    len(scores) is 4, so dividing the total by it gives the average score.

Answer: The loop ends with total = 28, and the program prints 7.0.

Takeaway: A for loop over a list hands you each item in turn; a running total divided by len gives the average.

Example 2 — When the count is the unknown

Standard

A program must find how many times 1,000 can be halved with integer division (n // 2) before the result drops below 10. A student starts writing for i in range(?) but cannot fill in the number. Solve the problem and say which loop fits.
Show the steps and the answer
  1. Notice that the number of passes is the answer itself, so it is not known before the loop starts.

    range needs its count up front, so a for loop cannot be set up honestly here.

  2. Use a while loop: n = 1000 and halvings = 0; while n >= 10: n = n // 2, then halvings = halvings + 1.

    The condition, not a fixed count, decides when the loop stops.

  3. Trace: 1000 → 500 → 250 → 125 → 62 → 31 → 15 → 7, which is 7 halvings; then the test 7 >= 10 fails.

    125 // 2 = 62 and 31 // 2 = 15, because integer division drops the half.

  4. Contrast: printing the first 7 halvings would suit for i in range(7), because there the count is given.

    The same steps fit a for loop as soon as the number of passes is known in advance.

Answer: 7 halvings, ending at 7. A while loop fits, because the number of passes is what you are trying to find.

Takeaway: If you can state the number of passes before the loop starts, use for; if the loop has to discover it, use while.

Example 3 — Find the mistake: a times table one line short

Application

Priya wants the 7 times table from 1 × 7 to 10 × 7. She writes for i in range(1, 10): print(i * 7), and her output ends at 63. Find the mistake and correct it.
Show the steps and the answer
  1. List what range(1, 10) produces: 1, 2, 3, 4, 5, 6, 7, 8, 9.

    range stops before its second number, so 10 is never reached.

  2. So the last line is 9 × 7 = 63, and 10 × 7 = 70 is missing.

    That is 9 passes, one short of the 10 lines she wanted.

  3. Fix: for i in range(1, 11): print(i * 7).

    The stop value must be one more than the last number you want.

  4. Check: range(1, 11) has 11 - 1 = 10 values, so the output runs from 7 to 70.

    The number of values in a range is stop minus start, a quick test for off-by-one errors.

Answer: Use range(1, 11). The loop then prints ten lines: 7, 14, 21, … , 70.

Takeaway: range(a, b) stops before b and gives b - a values; set the stop one past the last number you need.

Where You'll See It

  • Taking attendance

    FOR each student in the class list, call their name — the loop visits every item exactly once, which is what a for loop over a collection does.

  • Wrapping 10 party favors

    FOR each number from 1 to 10, wrap one favor; you know the count ahead of time, so a for loop is the natural fit.

  • Adding up your quiz scores

    FOR each score in your list of grades, add it to a running total — the loop variable automatically becomes each score in turn.

Common Mistakes

  1. The slip: range(5) produces 1, 2, 3, 4, 5.

    Why it's tempting: We naturally count from 1, so 'range of 5' sounds like the numbers 1 through 5.

    Instead: range(5) produces 0, 1, 2, 3, 4 — it starts at 0 and stops before 5, giving five values.

  2. The slip: It's safe to remove items from a list while looping over it.

    Why it's tempting: You're inside the loop with the item in hand, so deleting it right then seems efficient.

    Instead: Removing from the collection you're iterating shifts the indices and skips elements; loop over a copy or build a new filtered list instead.

  3. The slip: A for loop is the right choice when you don't know how many repetitions you need.

    Why it's tempting: For loops are the most common loop, so they feel like the default for any repetition.

    Instead: For loops fit a known count or a collection; when the stopping point depends on a runtime condition, a while loop is more appropriate.


Mini Practice

Try these on your own. Tap Reveal when you want to check.

  1. total = 0; for i in range(1, 6): total = total + i. What is total at the end?

    Hint: range(1, 6) stops before 6.

  2. What does for i in range(2, 11, 3): print(i) print?

    Hint: Start at 2, add 3 each time, and stop before 11.

  3. word = 'loop'; count = 0; for ch in word: if ch == 'o': count = count + 1. What is count at the end?

    Hint: The loop variable takes each character in turn.

  4. for i in range(3): for j in range(4): print('hi'). How many times is 'hi' printed?

    Hint: The inner loop runs completely for each pass of the outer loop.

  5. Task A: print each of the 30 names in a class list. Task B: keep rolling a die until a 6 appears. Which task suits a for loop?

    Hint: Which task has a known collection or count?

  6. A student wants to print 1 to 5 and writes for i in range(5): print(i). They expect 1, 2, 3, 4, 5. What prints, and how should it change?

    Hint: Where does range(5) start, and where does it stop?

Want the full set?

50 practice questions for this concept — free to try, every one with a complete worked solution showing the why, not just the answer.

Frequently Asked Questions

How do I get both the position and the item in a for loop?

In Python, use enumerate: for i, name in enumerate(names): gives i = 0 with the first name, i = 1 with the second, and so on. The older way, for i in range(len(names)): with names[i] inside, works but is easier to get wrong. JavaScript's for (let i = 0; i < names.length; i++) builds the counter by hand, which is why off-by-one mistakes turn up more often there.

Can a for loop count backwards or in steps?

Yes. In Python, range takes a start, a stop and a step: range(10, 0, -1) gives 10 down to 1, and range(0, 20, 5) gives 0, 5, 10 and 15. The stop value is still left out, which is why counting down to 1 needs a stop of 0. To walk through a list backwards without building the numbers yourself, use reversed(names).

Can I change the loop variable inside a Python for loop to skip ahead?

You can assign to it, but the next pass resets it. In for i in range(10):, writing i = i + 5 in the body changes i only until the loop hands out its next value, so every number from 0 to 9 is still visited. To skip an item, use continue, which jumps straight to the next pass, or build the right range in the first place.

Learning Path

For Loop

You are here

Next →

Array
You need Iteration (repeating a block of steps) and the While Loop (repeating while a condition holds, with a variable you update yourself) first. The for loop adds automatic stepping through a range or a collection, with the sequence fixed before the loop begins. Next, Arrays give the for loop its most common job: visiting every element of an ordered list, by value or by index.

See Also