Beginner   Chapter 62 · 25 min read · Module 5: Control Flow

Introduction to Loops

Learning objectives
  • After this chapter you can explain why loops are used and what problem they solve.
  • You can describe the idea of an iteration and the loop body.
  • You can tell when a for loop is a better choice than a while loop.
  • You can read a simple loop and predict how many times it runs.
  • You can name the common loop control tools: break, continue and else.

Computers are good at doing the same small job again and again without getting tired. Imagine you want to print the numbers from 1 to 100, or add up the marks of every student in a class, or keep asking a user for a password until it is correct. Writing one line of code for every repeat would be slow, boring and full of mistakes. A loop solves this by letting you write the work once and tell Python to repeat it.

Python has two kinds of loops. The for loop goes through the items of a collection or a range of numbers one by one. The while loop keeps running as long as a condition is true. Both repeat a block of indented code, which we call the loop body. Each time the body runs once, we say one iteration is complete.

This chapter is a gentle map of the whole topic. You will see what code looks like without a loop, how a loop improves it, how to choose between for and while, and which extra tools (break, continue and else) help you control the repetition. The next chapters study each loop type in detail.

The problem: repeating work by hand

Suppose you want to greet three friends. Without a loop you copy and paste the same kind of line again and again. This works for three names, but it is not realistic for three thousand. If you later want to change the greeting, you must edit every line, and it is easy to forget one.

Example 1: repeating by hand
print('Hello, Asha!')
print('Hello, Ravi!')
print('Hello, Meena!')
Hello, Asha! Hello, Ravi! Hello, Meena!

The lines above follow one pattern: only the name changes. Whenever you see a pattern like this in your code, it is a sign that a loop can replace the repeated lines. A loop keeps the pattern in one place, so a change needs to be made only once.

The same job with a loop

Here the names are placed in a list and a for loop visits each name. The variable name takes one value per iteration. The indented line is the loop body. Adding a fourth friend now means adding one word to the list, not a whole new line of logic.

Example 2: a for loop over a list
names = ['Asha', 'Ravi', 'Meena']
for name in names:
    print('Hello,', name + '!')
Hello, Asha! Hello, Ravi! Hello, Meena!
Iteration: one single run of the loop body. A loop that repeats five times has five iterations.
Loop body: the indented block of statements that Python repeats on every iteration.

Two kinds of loops

A for loop is used when you know what you want to go through: the letters of a word, the items of a list, or the numbers produced by range(). A while loop is used when you do not know in advance how many repeats you need, but you know the condition that must stay true, such as 'the balance is still above zero' or 'the user has not typed quit'.

QuestionUse
Do I have a collection or a fixed count?for loop
Do I repeat until something changes?while loop
Do I need the position number of each item?for loop with range() or enumerate()
Do I wait for user input to be valid?while loop
Example 3: a while loop with a counter
count = 1
while count <= 3:
    print('Round', count)
    count += 1
print('Done')
Round 1 Round 2 Round 3 Done

In a while loop you are responsible for changing the condition. In the example the line count += 1 moves the counter forward. If you forget it, the condition never becomes false and the loop never ends. This is called an infinite loop, and it is one of the most common beginner mistakes.

Parts of every loop

  1. Start: something is prepared before the loop, for example a counter set to zero or a list of items.
  2. Condition or sequence: Python checks whether another iteration is needed.
  3. Body: the indented code that does the work.
  4. Update: the state changes so that the loop can finish. A for loop does this for you; a while loop needs your help.

A very common job is to build up a result while looping. You create a variable before the loop, often called an accumulator, and change it inside the body. After the loop ends, the variable holds the final answer, such as a total or a count.

Example 4: an accumulator
total = 0
for n in [4, 8, 15, 16]:
    total += n
print('Total:', total)
Total: 43

Controlling a loop

Sometimes you want to leave a loop early or skip one iteration. The keyword break stops the whole loop immediately. The keyword continue skips the rest of the current iteration and jumps to the next one. Python also allows an else block on a loop, which runs only when the loop finished normally without a break. These tools are studied in later chapters, but a first look helps you recognise them.

Example 5: break and continue
for n in range(1, 8):
    if n == 3:
        continue
    if n == 6:
        break
    print(n)
1 2 4 5
Indentation is part of the syntax. Only the lines indented under the loop header repeat. A line written at the original indentation runs once, after the loop is finished.

Where loops appear in real programs

Loops are everywhere. A shopping site loops over the items in your cart to add up the price. A game loops many times each second to update the screen. A data tool loops over thousands of rows in a file. Learning loops well is therefore one of the biggest steps in becoming a confident programmer, because it turns small instructions into programs that can handle any amount of data.

As a rule of thumb, first ask what changes from one repeat to the next. Whatever changes becomes the loop variable or the state you update. Whatever stays the same belongs outside the loop or in the body unchanged. Thinking in this way will make the later chapters feel natural.

Python syntax

Syntax
for item in collection:
    statements
Syntax
while condition:
    statements
Syntax
for item in collection:
    statements
else:
    statements_if_no_break

Real-world applications

  • Adding up prices, marks or scores stored in a list.
  • Reading every line of a text file and processing it.
  • Asking a user again and again until the input is valid.
  • Repeating a game or menu until the player chooses to quit.
  • Processing every pixel, row or record in a data set.

Common mistakes

Mistake: Forgetting to update the variable used in a while condition, which causes an infinite loop.
Fix: Check that something inside the body moves the condition towards False, such as count += 1.
Mistake: Writing a statement at the wrong indentation, so it runs once instead of every iteration (or the reverse).
Fix: Indent exactly the lines that should repeat under the loop header, using four spaces.
Mistake: Forgetting the colon at the end of the for or while line.
Fix: Every loop header must end with a colon.
Mistake: Changing the list while looping over it, which can skip items.
Fix: Loop over a copy such as list(items), or build a new list.

Important tips

  • Name the loop variable clearly, for example for student in students.
  • Start with a small example and print values to see how each iteration behaves.
  • Prefer for loops when you can; they cannot forget the update step.
  • Test the first and the last iteration carefully, since many bugs hide there.

Key points summary

  • A loop repeats a block of code.
  • One run of the body is called an iteration.
  • for goes through a sequence; while repeats on a condition.
  • break leaves the loop; continue skips to the next iteration.
  • A while loop needs its condition to become false eventually.

Exam and interview points

  • Python has two loop statements: for and while.
  • The loop body is defined by indentation.
  • else on a loop runs only if the loop was not ended by break.
  • A loop with a condition that never becomes false is an infinite loop.

Quick revision

  • Loop = repeat code.
  • for = go through items.
  • while = repeat while true.
  • break stops, continue skips.
  • Indent the body.

Frequently asked questions

What is the difference between for and while?

A for loop visits each item of a sequence or range. A while loop repeats as long as a condition is true. Use for when you know what to go through and while when you wait for a condition.

Can a loop run zero times?

Yes. If the sequence is empty or the while condition is false at the start, the body never runs and Python moves on.

How do I stop an infinite loop?

In a terminal press Ctrl+C. Then fix the code so that the condition can become false or add a break.

Can I put one loop inside another?

Yes. This is called a nested loop. The inner loop runs fully for every single iteration of the outer loop.

Practise this chapter

17 practice questions Take the chapter quiz

Related chapters