All courses › Programming with Python › for loop and range

for loop and range

A for loop repeats code for each element in a sequence, often built with range(start, stop, step). The stop value is never included itself. Without start and step, range begins at 0 and counts up by 1.

range(a,b,s)\text{range}(a, b, s)the numbers a,a+s,a+2s,…a, a{+}s, a{+}2s, \ldots up to but not including bb

Symbols

aastart value (included)
bbstop value (not included)
ssstep

Example

for i in range(2, 8, 2): print(i)

prints 2 4 6 — 8 is not included.

The number of iterations of range(a, b, s) is ⌈(b−a)/s⌉\lceil (b-a)/s \rceil.
Practise loops and conditions for free →

← f-strings and formatting · while loop →

Part of Programming with Python: Loops and conditions.