Skip to content
Codewilds

Lesson 6 of 34 · Fundamentals

Python Loops: for, range() and while

medium20 XP3 min readFree lesson

Computers shine at repetition. Instead of writing the same line a hundred times, you write a loop. Python has two kinds: the for loop, which walks through a sequence of values, and the while loop, which repeats as long as a condition stays true.

The for loop

A for loop takes each item of a sequence in turn. A string, for example, is a sequence of characters:

for letter in "hiss":
    print(letter)
h
i
s
s

The indented block runs once per item, with letter holding the current character.

Counting with range()

range() produces a sequence of whole numbers — the most common way to loop a set number of times:

for i in range(3):          # 0, 1, 2
    print("Attack", i)

for n in range(1, 6):       # 1, 2, 3, 4, 5
    print(n)

for n in range(10, 0, -3):  # 10, 7, 4, 1  (start, stop, step)
    print(n)

The stop value is never included: range(1, 6) stops at 5. If you don't need the loop variable at all, name it _: for _ in range(3):.

The accumulator pattern

Many loops build up a result step by step: start with an empty or zero value, then update it on each pass.

total = 0
for n in range(1, 101):
    total += n
print(total)  # 5050

vowels = 0
for char in "serpent":
    if char in "aeiou":
        vowels += 1
print(vowels)  # 2

The while loop

A while loop repeats as long as its condition is true. Use it when you don't know in advance how many repetitions you'll need:

gold = 1
days = 0
while gold < 100:
    gold *= 2
    days += 1
print(days)  # 7

Something inside the loop must eventually make the condition false. Otherwise you get an infinite loop — here in the browser your run would stop with a timeout.

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of the current pass and jumps to the next one.
for n in range(1, 10):
    if n % 2 == 0:
        continue      # skip even numbers
    if n > 5:
        break         # stop completely
    print(n)          # prints 1, 3, 5

A common pattern is while True: combined with a break once some goal is reached.

Common mistakes

  • Off-by-one errors: range(1, 10) stops at 9. To include 10, write range(1, 11).
  • Forgetting to update the condition in a while loop, causing an infinite loop.
  • Wrong indentation: a return or print indented inside the loop runs on every pass; dedent it to run once after the loop ends.
  • Using / when you need whole numbers: n / 2 produces a float; use n // 2 to stay with integers.

Assignment

Write two loop-powered functions:

  1. sum_multiples(limit) returns the sum of all numbers from 1 up to and including limit that are divisible by 3 or 5. For example sum_multiples(10) is 3 + 5 + 6 + 9 + 10 = 33. If limit is less than 3, the sum is 0.
  2. collatz_steps(n) counts how many steps it takes to reach 1 from a positive integer n using these rules: if n is even, divide it by 2; if it's odd, replace it with 3 * n + 1. Starting at 6: 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1, which is 8 steps. collatz_steps(1) is 0.

Loops in other languages

Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.

Lesson last updated on .

Write code ↓
Python+20 XP

Press Run to execute your code, or Submit to check it against the tests.