Student Handbook

Student Handbook

Open in ChatGPT
Ask ChatGPT about this page
Open in Claude
Ask Claude about this page

range

Makes a sequence of whole numbers, most often for a for loop.

Synopsis

range(stop)
range(start, stop)
range(start, stop, step)

Description

range(3) gives 0, 1 and 2. It starts at 0 and stops before stop.

for i in range(n): is how Python repeats something n times, like Scratch's repeat block.

Parameters

Name Meaning
start The first number. The default is 0.
stop The number to stop before. It is not included.
step How much to add each time. The default is 1. It can be negative.

Return value

A range. Wrap it in list(...) to see all the numbers at once.

Example

for i in range(3):
    print(i)
print(list(range(1, 4)))
print(list(range(10, 0, -3)))

It prints:

0
1
2
[1, 2, 3]
[10, 7, 4, 1]

Common mistake

for i in range(1, 3):
    print(i)

It prints:

1
2

Only 1 and 2. stop is never included, so to count 1 to 3 write range(1, 4).

See also

len, Indexing and slicing

range in the Python documentation

Last updated 2 weeks ago