Latticework

Command Palette

Search for a command to run...

Python

Loops

12 min

Explanation

Python has two loop constructs: for, which iterates over any sequence (strings, lists, ranges...), and while, which repeats as long as a condition holds.

for i in range(5):
    print(i)   # 0 1 2 3 4

n = 0
while n < 3:
    print(n)
    n += 1

Most of the time you'll reach for for — it's harder to accidentally write an infinite loop with it.

Try it

A for loop accumulating a running total — one of the most common loop shapes you'll write.

Loading editor…
Explanation

Two keywords change a loop's flow:

  • break — exit the loop immediately.
  • continue — skip to the next iteration.

range(start, stop, step) is the usual way to loop a fixed number of times — range(5) is 0..4, range(2, 10, 2) is even numbers 2..8.

Exercise

Write a function `sum_to_n(n)` that returns the sum of all integers from 1 to n (inclusive), using a loop.

Exercise

Write a function `count_vowels(s)` that returns how many characters in the string s are vowels (a, e, i, o, u — case-insensitive), using a loop.

Quiz

What values does `range(3)` produce when iterated?

Checkpoint

You can write for/while loops and use break/continue to control them.