Lesson 14: Python loops: while and for
A loop repeats work. Use for when you know how many times, or when you are walking through a collection; use while when you repeat until something changes. range() is what makes counting loops short.
In short
- `for` repeats over a sequence or a `range()`; `while` repeats while a condition stays true.
- `range(1, 6)` gives 1 to 5 — the stop value is excluded, which is the most common off-by-one.
- A `while` loop needs something inside it that eventually makes the condition false, or it never ends.
- Accumulating a total inside a loop is the pattern behind factorials, sums and counts.
2
loop keywords in Python: for and while
Python docs
range(1, 6)
five numbers: 1, 2, 3, 4, 5
Python docs
Two loops, two purposes
A loop repeats a block of code. Python has two:
forrepeats once for each item in something — a range of numbers, a list, a string. Use it when you know what you are walking through.whilerepeats as long as a condition is true. Use it when the number of repetitions is not known in advance.
Counting with for and range
# loops.py — counting up, counting down, and a running total
for i in range(3):
print("for:", i)
total = 0
for number in range(1, 6):
total += number
print("sum 1 to 5 =", total)
n = 5
while n > 0:
print("while:", n)
n -= 1
print("lift off")
for i in range(1, 4):
for j in range(1, 4):
print(i, "x", j, "=", i * j)
How it works, step by step
range(3)produces 0, 1, 2. With one argument, range starts at 0 and stops before the number.range(1, 6)produces 1, 2, 3, 4, 5. The start is included, the stop is not.total += numberadds each value to a running total. That single pattern is the basis of summing, counting and multiplying.- The
whileloop prints 5, then 4, then 3, 2, 1. The linen -= 1is what moves it towards ending. - The nested loops run the inner loop three times for each of the three outer values, which is why nine lines appear.
What it prints
for: 0 for: 1 for: 2 sum 1 to 5 = 15 while: 5 while: 4 while: 3 while: 2 while: 1 lift off 1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9
Two worked examples
Factorial is a product, so the total starts at 1:
n = 5
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(n, "! =", factorial) # 5 ! = 120
Fibonacci keeps the last two values and adds them:
a, b = 0, 1
for _ in range(10):
print(a, end=" ")
a, b = b, a + b
print()
0 1 1 2 3 5 8 13 21 34
The underscore is an ordinary variable name used by convention when the loop value is not needed.
Common mistakes
- An infinite
whileloop: the condition never becomes false because nothing inside the loop changes it. Press Ctrl+C to stop it. range(1, n)where you meantrange(1, n + 1).- Indenting
print()inside the loop when you wanted a single total at the end. - Changing a list while looping over it. Loop over a copy (
for x in items[:]) or build a new list.
Practice
Try these before moving on. Each one uses only what this lesson covered.
- Program 8: calculate the factorial of a number with a for loop.
- Program 9: print the first ten numbers of the Fibonacci series.
- Print the multiplication table of 7 from 7 × 1 to 7 × 10.
- Add the numbers from 1 to 100 with a while loop, then check the answer with a formula.
Sources
Frequently asked questions
When should I use for instead of while?
Use for when you are walking through a known sequence or a fixed number of repetitions. Use while when you repeat until a condition changes, such as reading until a value is negative.
Why does range(1, 5) stop at 4?
range() always excludes its stop value. range(1, 5) gives 1, 2, 3, 4. To include 5, write range(1, 6).
How do I stop an infinite loop?
Press Ctrl+C in the terminal or stop the run button in IDLE. Then fix the loop: every while loop needs a line inside it that moves the condition towards being false.
Can a for loop change a list while looping over it?
It can, but the results are confusing because the list changes under the loop. Loop over a copy, or build a new list from the old one.