Technology Loops | Python Tutorial

Learn with diagrams, code, systems and practical examples.

</>
TutorialsPythonLoops
Core Python · Chapter 9

Loops

Repeat work with for and while loops.

Why this matters

Loops let you process collections, retry operations, and repeat steps without duplicating code.

Start with the idea

Use a for loop when iterating over known items. Use while when repetition depends on a condition that changes over time.

IdeaUnderstand the purpose
CodeRun the smallest example
PracticeChange it yourself
SubjectVision learning pattern: understand the idea before memorizing syntax.

Small working example

Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.

Python
prices = [5, 8, 12]
total = 0

for price in prices:
    total += price

print(total)
Expected output
25
What to notice

The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.

Common beginner mistake

Mistake

Using while when a simple for loop would be clearer, or forgetting to change the while condition.

Better approach

Choose the loop that best expresses the repetition and make loop progress obvious.

Quick recap

  • for iterates over items.
  • while repeats while a condition remains true.
  • Loops should have an obvious purpose and stopping condition.

Try it yourself

These are deliberately small. If you can complete them without copying the example, you are ready to continue.

  1. Print each item in a list.
  2. Write a countdown using while.
Deep chapter · Learn → Practice → Prepare → Test

Build a reliable mental model for Python loops

A loop is controlled repetition. Before memorizing syntax, ask two questions: what changes each iteration? and what makes the loop stop? A for loop normally consumes items from an iterable; a while loop keeps re-checking a condition that your code must eventually make false.

Use for when

You are processing items

The iterable supplies the next value. Lists, strings, dictionaries, files and range() objects can all participate in iteration.

orders = ["A100", "A101", "A102"]
for order_id in orders:
    print(order_id)

Expected output: A100, A101 and A102 on separate lines.

Use while when

Repetition depends on changing state

The condition is checked before every iteration. Make the state change easy to see, especially when continue is involved.

attempts_left = 3
while attempts_left > 0:
    print(attempts_left)
    attempts_left -= 1
print("done")

Expected output: 3, 2, 1, then done.

range() describes a sequence of integers; it does not build a list first

range(1, 4) produces 1, 2 and 3 when iterated. The stop value is exclusive. Python’s documentation also notes that a range object returns successive items as it is iterated rather than constructing the whole list in memory first.

1 included2 included3 included4 stop: excluded
for number in range(1, 4):
    print(number)

Expected output: 1, 2, 3.

Three control-flow ideas that beginners commonly mix up

continue

Skip the rest of the current iteration and ask for the next one. In a while loop, be careful not to skip the state update needed to reach the stopping condition.

break

Leave the nearest enclosing loop immediately. Use it when the reason for stopping is meaningful and visible in the code.

loop else

Run the else block only when the loop finishes without break. Think “search completed without an early break,” not “the loop condition was false.”

Original SubjectVision loop decision map A flow from choose repetition through for or while, inspect current item or condition, choose normal work, continue or break, then finish with loop else only if no break occurred. Choose repetitionitems or condition? fornext item whilere-check condition Run bodywork / continue / break No breakloop else may run breakloop else is skipped
SubjectVision original reference visual: follow the stopping reason, not just the syntax.
Interactive reference

Loop Tracer: watch state change one iteration at a time

Nothing is saved. Choose a preset, predict the next row, then step through the trace.

Ready. Predict the first iteration, then choose Step one iteration.
Preset
Normal for completion
Loop kind
for
Iteration
Not started
Item / state
Condition
Action
Next state
Output so far
Stopping reason
Loop else?
orders = [
    ("A100", "ready"),
    ("A101", "cancelled"),
    ("A102", "ready"),
    ("A103", "fraud-hold"),
]

for order_id, status in orders:
    print(order_id, status)

Expected result: the tracer’s final Output so far and stopping reason should match the selected program.

Beginner mistakes and fixes

MistakeWhat is really happeningBetter approach
Expecting range(1, 4) to include 4The stop value is exclusive.Trace the first, next and stop values before writing the loop.
Thinking range() creates a giant listA range object produces values as it is iterated.Convert to list(...) only when you actually need a list.
Changing the for target to control iterationThe iterable supplies the next item on the next iteration.Transform the value in another variable, or change the iterable/design.
Forgetting to update while stateThe condition may stay true forever.Make the progress update obvious and test the stopping boundary.
Putting continue before a required while updateThe update is skipped along with the rest of the body.Update before continue, or restructure the condition.
Reading loop else like if/elseLoop else is tied to whether break happened.Read it as “completed without break.”
Nesting loops before one loop is clearYou now have two changing iteration states to reason about.Trace each loop independently first; introduce nesting later.

When you need both position and item, prefer enumerate()

orders = ["A100", "A101", "A102"]
for position, order_id in enumerate(orders, start=1):
    print(position, order_id)

Expected output: 1 A100, 2 A101, 3 A102.

A manual index variable can work, but enumerate() states the intent directly and avoids another piece of state you must update correctly.

Practice → Prepare → Test

  1. Predict: before using the tracer, write what the next item, action and output should be.
  2. Modify: add an order after A103. Does it run in the normal, continue and break presets?
  3. Repair: write a while loop where continue accidentally skips the state update, then fix it.
  4. Explain: in one sentence, say why loop else runs after normal completion but not after break.

The current public test draws exactly 25 distinct randomized questions from the validated bank. Loop-specific candidates stay out of the public bank until their duplicate and quality review is complete.

Primary references

Semantics on this page are anchored to the official Python documentation. The interactive trace and visual are original SubjectVision learning aids.