Range function

Range function

range() is a function that generates a series of numbers within a certain range.

# Same loop as before, using range()
for i in range(5,0,-1):
	print(i)
print("Blastoff!")
5
4
3
2
1
Blastoff!

For longer lists of numbers, range is easier than typing the whole thing out.

The syntax for the range function is below.

range(start, stop, step)
  • start specifies the first value of the range.
  • stop specifies the stopping point.
    • The stop value is not included in the range, so range(1,10) will only go up to 9.
  • step specifies how much to count by each time. range(2,10, 2) produces 2, 4, 6, 8.
    • The default value is 1, which means that if you leave step out, range will count by 1.

Here’s some examples using range:

# Print the numbers 1-10
for n in range(1,11): # 11 is not included!
	print(n)

# Print the numbers 5, 10, 15, 20... 100, counting by 5s
for number in range(5, 101, 5):
	print(number)

# Print the numbers counting down from 5 to 1
for i in range(5,0,-1):
	print(i)
print("Blastoff!")

Range Practice