Loops
A for loop visits items in a sequence. range(1, 4) produces 1, 2, and 3; the stop value is excluded. A running total is a common reason to loop.
Repeat work with for and while loops and recognize when a loop stops.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: Loops
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
Suppose you want to add the numbers one, two, and three and report the running total. You could write three nearly identical additions, but the moment the list grows, copying lines becomes tedious and error prone. A loop keeps one set of instructions and repeats it for a sequence of values. This lesson will trace every pass through a for loop, including the state of the total after each addition. We will then use the same idea on real items in a list, stop a search early with break, and look at what nested loops really count. The important question is not simply how to spell for. It is what changes on each pass and what makes the repetition end.
- 00:41
Pause the video whenever we ask you to predict an output. You can run the matching examples in the Loops lesson console to compare your prediction with Python's actual behavior. Begin with total equal to zero. The expression range from one to four supplies one, two, and three. The stop argument, four, is excluded. On the first pass, number is one. Plus equals adds one to the existing zero, leaving one, and the indented print reports it. On the second pass, number is two. The same body adds two to the existing one, leaving three. On the third pass, number is three, so the new total is six. There is no fourth pass because the range has no more values.
- 01:25
The final print is outside the indentation, so it runs once after the loop. If you move that print inside, you will see a final-total line on every pass instead. A useful way to trace a loop is to draw columns for the changing variables and fill one row per pass. Now imagine a checklist stored as a list of three strings. A direct for loop can give you each step. You do not need to create indexes just to read the items. If the printed report needs numbers, enumerate gives you both the position and the item. With start set to one, the displayed labels are one, two, and three even though the list still uses zero-based indexing internally.
- 02:06
Predict what happens if a fourth step is appended: the loop simply makes one more pass. Some loops are searches, and continuing after the answer is found would waste work or even change the intended answer. In the lesson's appointment example, the first slot is closed, Tuesday is open, and Wednesday is also open. We set a default choice before the loop. When Tuesday is found, we store it and use break to leave the nearest loop immediately. The final print reports Tuesday. Without break, the later Wednesday match would replace it. If no slot is open, the default remains unchanged and the program reports that there is no open slot.
- 02:48
Nested loops mean a loop inside another loop. For two shelves with three positions each, the outer loop visits shelf one and shelf two. For each shelf, the inner loop visits positions one, two, and three, giving six labels in total. Do not add the counts; multiply them when every outer value pairs with every inner value. The lesson code prints one row per shelf because its print is outside the inner loop but still inside the outer one. Indentation tells you exactly how often each line executes. A while loop works differently: it repeats while a condition remains true. That is useful when you do not know in advance how many passes you need, but you must understand which value changes so the condition eventually becomes false.
- 03:35
The first common surprise is expecting the stop value of range to appear. Range from one to four gives one, two, three; range from one to five includes four. Say the starting value and the excluded boundary aloud before running. The second problem is a while loop that prints count while count is less than three but never changes count. If count begins at zero, the condition stays true and zero prints endlessly. Add count plus equals one inside the body. Now the passes use zero, one, and two, and the next test at three stops the loop. Notice that the update must actually affect the condition. Changing some unrelated variable will not help.
- 04:18
Be careful with break as well: it exits only the nearest enclosing loop, which matters in nested loops. Another subtle bug is resetting an accumulator inside the loop. If total becomes zero on every pass, you lose the previous work. Initialize it once before the loop, then update it inside. When a loop's result is wrong, trace the initial state, the values produced by the iterable, the body, and the exit condition in that order. A small table often reveals the mistake faster than staring at the entire program. In the practical task, change the starter range so the loop adds one through five.
- 04:58
Predict the running totals before you run: one, three, six, ten, and fifteen. The final total must be fifteen. Press Check Task after the run, and use its feedback if the output differs. For an extra challenge, make a list of three study topics and print each with enumerate starting at one. Then ask whether you would use break if you only wanted the first topic whose name includes the letter s. The quiz tests the excluded stop value, the number of passes, and break. Treat each question as a miniature execution trace: list the values, follow the indentation, and stop at the exact point Python stops. The next lesson wraps reusable instructions inside functions, so you will be able to run the same logic with different inputs without copying an entire loop.
Understand the concept
A while loop repeats while its condition remains true. Its body must eventually change something that makes the condition false. break can end a loop early when needed.
- for iterates over values
- range stop is excluded
- while needs a stopping condition
See it step by step
Read the code, predict the output, then compare it with the result.
01. Visit a range
for number in range(1, 4):
print(number * 2)2
4
6range(1, 4) provides 1, 2, and 3; the stop value 4 is excluded.
02. Accumulate a total
total = 0
for value in [2, 3, 4]:
total += value
print(total)9Each iteration adds the next list item to total. The final print runs after the loop.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Iterate over values and count positions only when needed
A loop over a list gives you each item directly. You do not need to build a range of numeric indexes merely to read its values. When the position is useful for a numbered report, enumerate() gives you both the number and the item. The start argument changes the displayed numbering without changing the list or its zero-based indexes.
This pattern is handy for menus, checklists, and ranked results. It also keeps the label attached to the value, so you are less likely to read the wrong list element. Predict what happens if you append 'Review' to the list below. Then change start=1 to start=0 and compare the output with the list's actual indexes.
steps = ["Write code", "Run tests", "Share result"]
for position, step in enumerate(steps, start=1):
print(f"{position}. {step}")1. Write code
2. Run tests
3. Share result- enumerate() yields a position and a value on each pass.
- The loop body formats one numbered line for each step.
Stop early when the answer is known
Some searches do not need every item. A break statement exits the nearest loop immediately. That is useful when you need the first matching result, such as the first open appointment. Put a default result before the loop, replace it when a match appears, and stop. Code after the loop can then use the result regardless of whether a match was found.
Without break, a later match could overwrite the first one. The placement of print also matters: here it runs once after the search, rather than once per slot. Move the available slot to the last position and check whether the final answer still works. Then try a list with no open slot and observe the default message.
slots = [("Monday", False), ("Tuesday", True), ("Wednesday", True)]
choice = "No open slot"
for day, is_open in slots:
if is_open:
choice = day
break
print(choice)Tuesday- Monday is closed, so the loop continues.
- Tuesday is open; choice changes and break skips Wednesday.
- The print statement runs once after the loop.
Nested loops describe combinations
A loop inside another loop visits every combination of their values. Think of shelves and positions: for each shelf, visit every position on it. The inner loop finishes all of its turns before the outer loop moves to the next shelf. This is a natural way to generate coordinates, small tables, or pairs of settings.
The number of body executions multiplies: two shelves times three positions means six labels. That cost becomes important if both inputs grow large. The example collects labels for one shelf, then joins them into a line. Change the outer range to four shelves and predict the new number of labels.
for shelf in range(1, 3):
labels = []
for position in range(1, 4):
labels.append(f"{shelf}-{position}")
print(" ".join(labels))1-1 1-2 1-3
2-1 2-2 2-3- The outer loop chooses shelf 1, then shelf 2.
- For each shelf, the inner loop visits positions 1, 2, and 3.
- join places spaces between the labels, and print starts a new output line for the next shelf.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
range(1, 6) produces 1 through 5. Keep total += number inside the loop, then print the final total after the loop.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
A while loop never progresses
count = 0
while count < 3:
print(count)count = 0
while count < 3:
print(count)
count += 1What happens: The condition stays true, so the loop keeps printing 0.
Update the value tested by the condition.
Expecting the stop value
for n in range(1, 4):
print(n)
# Expecting 1, 2, 3, 4for n in range(1, 5):
print(n)What happens: Only 1, 2, and 3 appear.
range excludes its stop argument.