Skip to content
GetITechSkills

Logic and Programming

Loops Explained: Repeating Work in Code

Beginner · Concept · 6 min read · Updated October 30, 2026

Picture a cashier scanning the items in your basket. She does not invent a new procedure for each item. She does the same thing again and again: pick up an item, scan it, put it down, until the basket is empty. A computer is very good at this kind of repetition. It never gets bored, and it does not skip the fortieth item because it lost focus.

In code, the tool for repetition is the loop. A loop runs a block of steps more than once. This entry explains the two main kinds, how each one decides when to stop, and the mistakes that cause a loop to run forever or to stop one step too early. The examples use a shopping cart and a savings goal.

Why loops exist

Without loops, you would repeat code by copying it. To add up three prices, you would write three lines. To add up three thousand, you would write three thousand lines, and you would have to rewrite them every time the number of items changed. A loop lets you write the step once and say how many times, or for which items, to run it.

Every loop has the same three parts, even when the syntax hides them:

  1. A way to start: where the loop begins, or which item comes first.
  2. A step: the work done on each pass. One pass through the loop is called an iteration.
  3. A way to stop: a condition or an end of data, so the loop does not run forever.

When a loop misbehaves, the cause is almost always in the first or the third part.

The for loop: once per item

Use a for loop when you know what to go through: every item in a list, every letter in a word, every number in a range. Here is a cart total:

prices = [4.50, 2.25, 10.00]
total = 0

for price in prices:
    total = total + price

print("Total:", total)

Follow it by hand. The variable total starts at 0. On the first pass price is 4.50, so total becomes 4.5. On the second pass price is 2.25 and total becomes 6.75. On the third pass price is 10.0 and total becomes 16.75. The list is now used up, so the loop ends. The output is Total: 16.75.

The name price is chosen by you. It is a variable that takes the next item from the list at the start of each pass. Names like this one read well because they say what one item is.

Counting with range

Sometimes you want to repeat something a set number of times, with a counter. The range function produces a sequence of numbers for that:

for day in range(1, 4):
    print("Day", day)

This prints:

Day 1
Day 2
Day 3

Notice that range(1, 4) starts at 1 but stops before 4. Python ranges include the start and exclude the end. That feels odd at first, and it is the source of many "off by one" errors. A handy check: the number of passes is the end minus the start, so 4 minus 1 gives 3.

JavaScript spells the same idea with an explicit start, stop condition and step in one line: for (let day = 1; day < 4; day++). That line shows the three parts of a loop very clearly.

The while loop: until a condition changes

Use a while loop when you do not know in advance how many passes you will need. The loop keeps going as long as its condition is true, and the condition is checked before every pass.

Suppose you want to save at least 200, putting aside 60 each week:

saved = 0
weeks = 0

while saved < 200:
    saved = saved + 60
    weeks = weeks + 1

print(weeks, "weeks, saved", saved)

Trace it with a table of the values at the end of each pass:

Pass saved weeks Is saved < 200 afterward?
1 60 1 Yes, continue
2 120 2 Yes, continue
3 180 3 Yes, continue
4 240 4 No, stop

The output is 4 weeks, saved 240. You could not have used a simple for loop here without first working out the number of weeks, which is the very thing you wanted the program to find.

Choosing between for and while

Situation Better fit
Go through every item in a collection for
Repeat a fixed number of times for with range
Repeat until something changes, with an unknown count while
Keep asking until the input is valid while

If you can describe the job as "for each ... do ...", reach for for. If you describe it as "keep doing ... until ...", reach for while.

Stopping early and skipping

Two keywords give you finer control inside a loop.

break ends the loop immediately. It is useful when you have found what you need. This finds the first item in the cart that costs more than 5:

for price in prices:
    if price > 5:
        print("First expensive item:", price)
        break

The first price, 4.5, is not above 5. The second, 2.25, is not either. The third, 10.0, is, so the program prints First expensive item: 10.0 and leaves the loop.

continue skips the rest of the current pass and moves to the next one. Here a free sample with a price of 0 is skipped:

for price in [4.50, 0, 2.25]:
    if price == 0:
        continue
    print("Charging", price)

The output is Charging 4.5 followed by Charging 2.25. The zero never reaches the print line. Both keywords combine loops with the decisions covered in the entry on if and else. JavaScript has the same two keywords with the same meaning.

Loops inside loops

You can place one loop inside another. For every pass of the outer loop, the inner loop runs completely. If the outer loop runs 3 times and the inner one 4 times, the inner steps run 12 times in total. Nested loops are useful for tables and grids, but the work grows fast, so keep an eye on the numbers. Looping over collections such as lists and dictionaries is where you will use loops most often.

Common mistakes

  • Forgetting to change the condition. In a while loop, if nothing inside the loop ever makes the condition false, it runs forever. In the savings example, deleting the line saved = saved + 60 would freeze the program. If that happens in a terminal, press Ctrl+C to stop it.
  • Off-by-one counting. range(1, 4) gives three passes, not four. When the count looks wrong by one, check whether the end value is included.
  • Changing a list while looping over it. Adding or removing items from the list you are walking through can skip items or repeat them. Build a new list instead.
  • Starting the total in the wrong place. If total = 0 sits inside the loop, it resets on every pass and you only get the last price.
  • Doing too much inside the loop. Work that could be done once, such as reading a file, belongs before the loop. Repeating it needlessly makes the program slow.
  • Using a loop when a built-in does the job. Python has sum(prices), which gives 16.75 for the cart. Learning the loop first is right, but check for a ready-made tool afterward.

FAQ

What is the difference between a for loop and a while loop?

A for loop goes through a known set of items or a counted range. A while loop repeats until its condition becomes false. Either can do the other's job, but each is clearer in its own case.

What is an infinite loop?

It is a loop whose stopping condition is never reached, so it never ends. Some programs use one on purpose, such as a game that runs until you quit, but an accidental one just freezes the program.

What does iteration mean?

An iteration is one pass through the body of a loop. "Iterate over a list" means to visit each item once.

Can I repeat a block without a loop?

Yes. You can put the steps in a function and call it several times. That is not a loop, though, and it does not scale to thousands of repeats. The entry on reusable functions covers that approach.

How do I know how many times a loop ran?

Keep a counter variable, as the savings example does with weeks. For lists, Python's len() gives the number of items, which equals the number of passes for a simple for loop. For the other building blocks of code, see the Logic and Programming area.

Sources

  1. More Control Flow Tools: for Statements, range(), break and continue (opens in a new tab) — Python Software Foundation (docs.python.org). Official tutorial chapter on for loops, range() and loop control
  2. Loops and iteration (JavaScript Guide) (opens in a new tab) — MDN Web Docs (Mozilla). How JavaScript writes for, while, do...while, break and continue
  3. Data Structures: Looping Techniques (opens in a new tab) — Python Software Foundation (docs.python.org). Ways to loop over lists and dictionaries in Python

Next in Logic and Programming: Functions Explained: Reusable Pieces of Code

  • Logic and Programming

    If and Else: How Programs Make Decisions

    Learn how if, elif and else let a program choose between paths, how comparisons and and/or/not work, and the mistakes that break decisions.

    • Beginner
    • Concept
    • 6 min read

    Updated October 30, 2026

  • Logic and Programming

    Functions Explained: Reusable Pieces of Code

    A function is a named block of code you can run again and again. Learn parameters, return values, scope and why functions keep programs tidy.

    • Beginner
    • Concept
    • 6 min read

    Updated October 30, 2026