livepython.net
CHAPTER 10For Loops
10.2  RANGE()

Python range() Function in a for Loop

Repeat Code n Times with range()

The range() function makes a row of whole numbers for a for loop to go through. range(5) gives 0, 1, 2, 3, 4: five numbers, starting at 0.

PYTHONedit me
for i in range(5):
    print(i)
OUTPUT
0
1
2
3
4

Think of it like the tickets at a counter: the machine hands out ticket 0, then 1, then 2, until it has given out as many as you asked for.

The rules

  • range(n) gives n numbers: from 0 up to n - 1.
  • The number n itself is not included. range(5) stops at 4.
  • i is the usual name for a loop variable that only counts.

Repeat something n times

Often you don't even need the number. You only want the block to run a certain number of times:

PYTHONedit me
for i in range(3):
    print("Hip hip hooray!")
OUTPUT
Hip hip hooray!
Hip hip hooray!
Hip hip hooray!

Change 3 to 10, and the cheer runs 10 times. No copying and pasting.

Why start at 0?

It matches list indexes from chapter 9: the first item is at index 0. You'll see in the last lesson of this topic how that helps. And if you want to start at 1, the next lesson shows you how.

Common beginner doubt: "Does range(3) make a list?" Not quite. It's a range: it hands out its numbers one at a time, when the loop asks for them. For a for loop, it works just like a list of numbers.

range(n) gives n numbers, from 0 up to n - 1.

your turnPredict the output

What will this print?

for i in range(3): print(i)
Your turn! What will this code show on the screen?
your turnFill the gap

Print Hi exactly 4 times

for i in range(?): print("Hi")

It should print: Hi Hi Hi Hi

Which piece makes this code work?

range() with a Start and a Stop

Give range() two numbers, and you choose where it starts: range(start, stop). It begins at start and stops just before stop.

PYTHONedit me
for i in range(1, 6):
    print(i)
OUTPUT
1
2
3
4
5

Think of it like the floors in a lift ride from floor 1 to floor 6: you pass floors 1, 2, 3, 4 and 5, and you step out as the doors open on 6. The stop floor isn't part of the ride.

The rules

You writeYou get
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(10, 13)10, 11, 12
range(5, 5)nothing: the loop doesn't run
  • start is included. stop is not.
  • How many numbers? stop - start. range(1, 6) gives 6 - 1 = 5 numbers.
  • To count from 1 to n, write range(1, n + 1).

Off by one

The most common range() mistake is stopping one number too early:

PYTHONedit me
for i in range(1, 10):
    print(i, end=" ")
OUTPUT
1 2 3 4 5 6 7 8 9

You wanted 1 to 10, but 10 is the stop, so it's left out. This is called an off-by-one mistake. The fix is range(1, 11).

Use the number

The loop variable is a real number, so you can calculate with it. Here are the first five square numbers, with ** from chapter 5:

PYTHONedit me
for n in range(1, 6):
    print(n, "squared is", n ** 2)
OUTPUT
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

range(start, stop) includes the start and stops just before the stop.

your turnType the output

Type what this prints

for i in range(3, 6): print(i)
Read the code line by line, then type the output exactly.
your turnFix the code

Make it print the numbers 1 to 5, one per line

It should print: 1 2 3 4 5

for i in range(1, 5):
    print(i)
This code does not work yet. Fix it, then press Run.

Counting in Steps and Backwards

A third number sets the step: how much to add each time. range(start, stop, step) jumps by step instead of by 1.

PYTHONedit me
for i in range(0, 11, 2):
    print(i, end=" ")
OUTPUT
0 2 4 6 8 10

Think of it like climbing stairs two at a time: you still go up, but you only land on every second step.

The rules

You writeYou get
range(0, 11, 2)0, 2, 4, 6, 8, 10
range(1, 10, 3)1, 4, 7
range(5, 0, -1)5, 4, 3, 2, 1
range(10, 0, -2)10, 8, 6, 4, 2
  • The stop is still not included, whichever way you count.
  • A negative step counts backwards. Then the start must be bigger than the stop.
  • The step can't be 0: Python would never get anywhere.

A countdown

PYTHONedit me
for i in range(5, 0, -1):
    print(i)
print("Liftoff!")
OUTPUT
5
4
3
2
1
Liftoff!

The stop is 0, so the countdown ends at 1. Write range(5, -1, -1) if you want the 0 too.

Counting the wrong way

Count backwards without a negative step, and you get nothing at all:

PYTHONedit me
for i in range(5, 0):
    print(i)
print("end")
OUTPUT
end

No error, but no numbers either. With the normal step of 1, Python can't get from 5 up to 0, so the range is empty and the loop never runs.

Common beginner doubt: "Can the step be a decimal, like 0.5?" No. range() only works with whole numbers (ints). You'll learn another way to count in small steps with while loops in chapter 11.

range(start, stop, step) jumps by step; a negative step counts down.

your turnPredict the output

What will this print?

for i in range(1, 8, 3): print(i)
Your turn! What will this code show on the screen?
your turnPick the right idea

Which range() counts 10, 9, 8 … down to 1?

Think about it, then pick one.

range() with Input and List Indexes

The numbers in range() don't have to be fixed. They can come from input or from len(), so the program decides at run time how many times to loop.

Think of it like a printer: you type how many copies you want, and the printer repeats the page exactly that many times.

A times table for any number

PYTHONedit me
n = int(input())
for i in range(1, 6):
    print(n, "x", i, "=", n * i)
OUTPUT
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

Type another number in the Input box and run it again.

Read several inputs

Put input() inside the loop, and it runs once per iteration. Here the first line says how many prices follow:

PYTHONedit me
count = int(input())
for i in range(count):
    price = int(input())
    print("Item", i + 1, "costs", price)
OUTPUT
Item 1 costs 40
Item 2 costs 25
Item 3 costs 60
  • range(count) makes the loop run count times.
  • Each iteration reads one line of input.
  • i + 1 turns the 0, 1, 2 from range() into the friendlier 1, 2, 3.

Loop over list indexes

range(len(names)) gives every index of a list: 0, 1, 2, and so on. Then names[i] is the item at that index (chapter 9):

PYTHONedit me
names = ["Sunny", "Rocky", "Lucky"]
for i in range(len(names)):
    print(i + 1, names[i])
OUTPUT
1 Sunny
2 Rocky
3 Lucky

When you only need the items, for name in names: is simpler. Use the index version when you need the position too.

Feed range() a number from input() or len(), and the loop fits the data.

your turnOrder the lines

Put the lines in order to read 2 names and greet each one

  1. name = input()
  2. print("Hi", name)
  3. for i in range(count):
  4. count = int(input())

The user types: 2SunnyRocky

These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

age = 15 if age >= 18: print("adult") elif age >= 13: print("teen") else: print("child")
Your turn! What will this code show on the screen?

Practice: range()

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 82.Python Program to Print Numbers from 1 to NEasySolve
  2. 83.Python Program to Print a Multiplication TableEasySolve
  3. 84.Python Program to Print a CountdownMediumSolve