Lesson 13 of 30 · Loops
The range Function
Use Python's range() to repeat code a set number of times. Learn start, stop and step, how to count backwards and why the stop value is left out.
- 7 min read
- Beginner
- Reviewed
- How to repeat code an exact number of times
- The three forms of range(): stop, start and stop, and start, stop and step
- Why range() stops one number early
- How to count backwards
Repeating a set number of times
A for loop needs something to loop over. But sometimes you have no list. You just want to do something five times, or count from 1 to 100.
range() produces a sequence of numbers for exactly this purpose.
for number in range(5):
print(number)Two things may surprise you:
- Counting starts at 0, as it does for string and list positions.
- The loop stops before 5. You get five numbers: 0, 1, 2, 3 and 4.
Doing something N times
If you only want repetition and do not care about the number, you can ignore the loop variable.
for attempt in range(3):
print("Trying again...")
print("Finished after 3 attempts.")Choosing where to start
Give range() two numbers to set the start and the stop.
for number in range(1, 6):
print(number)This prints 1 to 5. To count from 1 to 10 you write range(1, 11): the stop is always one more than the last number you want.
Choosing the step
A third number sets the step, the amount added each time.
print("Even numbers:")
for number in range(0, 11, 2):
print(number)
print("Counting in fives:")
for number in range(5, 26, 5):
print(number)Counting backwards
A negative step counts down. The start must be the larger number.
for seconds in range(5, 0, -1):
print(seconds)
print("Liftoff!")The loop stops before 0, so the last number printed is 1.
The three forms side by side
range() on its own does not show its numbers when printed. Wrap it in list() to see them.
print(list(range(5))) print(list(range(2, 7))) print(list(range(0, 20, 5))) print(list(range(10, 0, -2)))
Using the number in calculations
The loop variable is an ordinary number, so you can calculate with it. This prints a times table.
table = 7
for number in range(1, 11):
print(f"{table} x {number} = {table * number}")Adding up a range
Combine range() with the running-total pattern from the last lesson.
total = 0
for number in range(1, 11):
total += number
print("1 + 2 + ... + 10 =", total)Common mistakes
Use range() and a running total to add the numbers from 1 to 100, then print the result.
# Add up every whole number from 1 to 100 # and print the answer. Output must be exactly: 5050
Which numbers does range(2, 6) produce?
Summary
range(stop)counts from 0 up to, but not including,stop.range(start, stop)chooses the first number.range(start, stop, step)chooses the gap. A negative step counts down.- The stop value is never included.
list(range(...))shows the numbers a range contains.
Next: loops that keep going until something changes.
Finished reading? Tick it off to track your progress.