One-sentence summary
A loop lets us tell the computer to do the same job again and again — either "this many times" or "as long as this condition is true" — and in Python we do this with for and while.
Why it matters
Imagine you want a program to print the numbers from 1 to 100. Writing each line by hand as print(1), print(2), print(3) would take forever and it is easy to make a mistake. Loops are exactly what solve this.
In the Scratch module we used the "repeat 10 times" block. for and while are the Python version of that same idea. Reading a robot's sensor over and over, drawing every frame in a game, or printing each name in a list — all of these are done with loops. Repetition was one of the three basic building blocks of programming; in this lesson we turn it into real code.
The for loop: a set number of repeats
A for loop is used to repeat something a known number of times, or to go over an existing sequence. In plain words: "for each item, do this."
Counting with range
The range(...) function gives us a sequence of numbers. range(5) produces 0, 1, 2, 3, 4 — it starts at 0 and stops before reaching 5.
for i in range(5):
print("Hello", i)
The output of this code:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Here i is a counter and takes the next value on each pass. Notice that the print line is written 4 spaces in from the for line. This indentation tells Python that the line is inside the loop. If you remove the indentation, the code will not run.
range can be used in three ways:
range(5)→ 0, 1, 2, 3, 4range(1, 6)→ 1, 2, 3, 4, 5 (from a start to an end)range(0, 10, 2)→ 0, 2, 4, 6, 8 (in steps of two)
Example: sum from 1 to 10
We can collect the counter values in a variable.
total = 0
for i in range(1, 11):
total = total + i
print("Total:", total)
range(1, 11) gives us the numbers from 1 to 10. On each pass we add i to total. The program prints Total: 55.
Looping over a list
for works not only with numbers, but also with each item of a list. We will cover lists in detail in the next lesson; for now, think of them as items lined up inside square brackets.
names = ["Ada", "Deniz", "Kaan"]
for name in names:
print("Next:", name)
This code prints each name one by one:
Next: Ada
Next: Deniz
Next: Kaan
Here the loop variable is not a number but the item itself. The loop runs once for each item; we do not need to know the count ourselves.
The while loop: as long as a condition is true
A while loop repeats as long as a condition stays true. It is useful when we do not know in advance how many times it should run. We write a condition just like the if you remember from the Conditions lesson; the difference is that the work repeats while the condition is true.
number = 1
while number <= 3:
print("Number:", number)
number = number + 1
Its output:
Number: 1
Number: 2
Number: 3
Three things matter here: a starting value (number = 1), a condition (number <= 3), and a line that changes the value on each pass (number = number + 1). Without that last line, the condition would never break.
Example: sum from 1 to 10 (with while)
We can do the same sum with while too. This lets you compare the logic of the two loops.
total = 0
number = 1
while number <= 10:
total = total + number
number = number + 1
print("Total:", total)
The result is again Total: 55. We solved the same problem with both for and while. When the count is known, for is usually shorter; when you do not know whether it will stop based on a condition, while fits better.
break, continue and the infinite loop
break: end the loop right away
break is used to say "that's enough, get out" in the middle of a loop.
for i in range(1, 100):
if i == 5:
break
print(i)
This code prints 1, 2, 3, 4 and stops the loop completely once i becomes 5.
continue: skip this pass
continue skips the rest of the current pass and moves on to the next one.
for i in range(1, 6):
if i == 3:
continue
print(i)
The output is 1, 2, 4, 5; the 3 is skipped, but the loop keeps going.
The risk of an infinite loop
If a while loop's condition never breaks, the program never stops. This is called an infinite loop.
number = 1
while number <= 5:
print(number)
# if the line number = number + 1 is forgotten, the loop never ends
In the code above, number stays 1 forever, so the condition is always true and the screen keeps printing 1. To stop the program, you can press Ctrl + C in the terminal. Whenever you write a while, ask yourself: "How will this condition ever break?"
Mini practice
Try these three tasks on your own computer:
- Using
forandrange, print the even numbers from 1 to 20. (Hint:range(2, 21, 2).) - Make your own list: write
animals = ["cat", "dog", "bird"]and useforto print each animal. - Using
while, count down from 10 to 1. Decrease the value by 1 on each pass.
One solution to the second task could be:
animals = ["cat", "dog", "bird"]
for animal in animals:
print(animal)
Run your own solution and check whether the output is what you expected.
Common mistakes
Forgetting the indentation
The lines inside the loop must be 4 spaces in. Without indentation, Python gives an IndentationError.
Forgetting that range does not include the last number
range(1, 10) does not include 10; it stops at 9. For 1 to 10 you must write range(1, 11).
Forgetting to update the counter in a while
Without a line like number = number + 1, the condition never changes and you create an infinite loop.
Mixing up for and while
When you know how many times to repeat, for is clearer. When it should stop based on a condition, while fits better.
Safety note
This lesson is entirely about Python code that runs on your own computer. Only run code that you wrote yourself or that you trust; do not run code copied from the internet without understanding it. If a program stops responding (for example, it enters an infinite loop), you can safely stop it with Ctrl + C. Do not write your personal information inside the code.
Review questions
- When is a for loop a clearer choice than a while loop?
- What must change inside a while loop so that it can finish?
- How does range stop before its final boundary in Python?
- What test exposes an off-by-one mistake in a loop?
- Why is modifying a list while iterating through it risky?
- How can break and continue change the normal loop flow?
Answers
- Use a for loop when processing a known sequence or a known number of repetitions.
- The value used by the condition must eventually move toward the stopping condition.
- The stop value is excluded, so range(0, 5) produces 0 through 4.
- Test the smallest valid input and the first value beyond the expected boundary, then count the actual repetitions.
- Items can shift or be skipped, making the behaviour hard to predict; build a new list or iterate over a copy instead.
- break ends the loop immediately, while continue skips the rest of the current repetition and starts the next one.
Lesson summary
- A
forloop is used to repeat a set number of times or to go over the items of a sequence or list. range(start, stop, step)produces a sequence of numbers and stops before reaching the stop value.- A
whileloop repeats as long as a condition is true and needs a line that changes the condition. breakends the loop completely;continueskips only the current pass.- A
whilewhose condition never breaks creates an infinite loop, which you can stop withCtrl + C.
Check your understanding
- Which numbers does
range(3)produce? - How many times does the loop
for i in range(1, 6):run? - What must be present in the code so that a
whileloop does not run forever? - What is the difference between
breakandcontinue? - Write a short piece of code that prints the list
["blue", "green"]with aforloop.
Answers
- It produces 0, 1 and 2.
rangestarts at zero and stops before reaching 3. - It runs 5 times:
itakes the values 1, 2, 3, 4, 5 in turn (range(1, 6)does not include 6). - There must be a line that eventually breaks the condition, for example
number = number + 1, which changes the counter on each pass. breakstops the whole loop immediately;continueonly skips the rest of the current pass and moves on to the next one.- Example solution:
colors = ["blue", "green"]
for color in colors:
print(color)
Source and verification note
For “For and While Loops”, verification focuses on whether the relationship between The for loop: a set number of repeats and Example: sum from 1 to 10 remains consistent across examples. Code examples follow Python 3 syntax. Small differences may appear between environments, so examples should first be tested in a safe online editor or a local development setup.
Next lesson
Lists and Dictionaries: We will learn to store data in ordered lists and in key-value pairs, and to process that data with loops.