Learning LibraryCore Coding LibraryKids

The range() function: a counter for your loops

A loop needs something to count with. range() is that counter. Tell it how many, and it hands your loop one number at a time.

The big idea

range(n) gives a loop the whole numbers from 0 up to, but not including, n.

See it in code

1Start simple

range(6) means six trips. It counts 0, 1, 2, 3, 4, 5, which is six numbers, starting at zero:

python
tray_size = 6

for cookie_number in range(tray_size):
    print("Cookie number", cookie_number)
A tray of six cookies:
Cookie number 0
Cookie number 1
Cookie number 2
Cookie number 3
Cookie number 4
Cookie number 5

The last number is 5, not 6. A range stops just before the number you give it. Count the lines, though, and there are still six.

2A step further

len(menu) counts a list. Hand that to range() and the loop walks through every position, so you can number a menu:

python
menu = ["brownie", "cookie", "muffin"]

for spot in range(len(menu)):
    print(f"{spot + 1}. {menu[spot]}")
A numbered menu for ordering:
1. brownie
2. cookie
3. muffin

spot went 0, 1, 2. People count from 1, so the menu shows spot + 1. The list itself still counts from 0.

3In the paint studio

The counter can change y as easily as x. Multiply it by a gap and a column of bolts runs down the robot's side:

python
bolt_count = 4
bolt_top = 190
bolt_gap = 30

paper("wheat")
box(x=200, y=235, width=170, height=170, color="silver", corner=18)
for count in range(bolt_count):
    ring(x=140, y=bolt_top + count * bolt_gap, size=12, color="dim gray", width=3)
Four bolts, one line of paint:
A silver robot body with four small gray ring-shaped bolts running down its left side, on wheat-colored paper.

The first bolt uses count = 0, so it lands right at bolt_top. Each bolt after that is one gap lower.

The same idea, everywhere

Any time you want something to happen a set number of times, range() does the counting. Twelve cookies, eight bricks across, five rounds of a game.

Try it yourself

Change bolt_count to 6 and run it. The bolts run off the robot. Now make bolt_gap smaller until all six fit. One number changed the count, and another changed the spacing.

The common mistake

Expecting range(6) to end at 6. It ends at 5. If you need the numbers 1 to 6, use the counter plus one, like spot + 1 in the menu.

What it unlocks

range() is the engine inside most for loops. Two of them together make loops inside loops, and range(len(...)) is the key to getting items from a list.

Older, or want more depth? Read the Teens version →