Menu
Coddy logo textTech

The Range Function

Part of the Fundamentals section of Coddy's Python journey — lesson 40 of 77.

The range() function in Python generates a sequence of numbers, which is commonly used with for loops to repeat code a specific number of times.

Create a range that starts at 0 and ends at 4:

for i in range(5):
    print(i)

This will output:

0
1
2
3
4

You can also specify a start value:

for i in range(2, 6):
    print(i)

This will output:

2
3
4
5

And you can specify a step value (increment):

for i in range(1, 10, 2):
    print(i)

This will output:

1
3
5
7
9

Counting Backwards (Descending Order):

You can also use a negative step value to count backwards. When using a negative step, the start value must be greater than the end value:

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

This will output:

10
9
8
7
6
5
4
3
2
1

You can also use larger negative steps:

for i in range(20, 9, -2):
    print(i)

This will output:

20
18
16
14
12
10

Notice that 10 is included in the output even though the end value is 9. This is because the end value is exclusive — the loop continues as long as the current value is greater than the end value. Since 10 > 9, it is printed. The next step would be 8, which is not greater than 9, so the loop stops.

Key Point: When using a negative step, the start value must be greater than the end value. The end value is still exclusive (not included).

challenge icon

Challenge

Beginner

Write a for loop that prints numbers using the range() function. Your program should:

  1. Read three numbers as input: start, end, and step
  2. Use a for loop with range(start, end, step) to print all numbers from start to end (not including end) with the given step increment
  3. Print each number on a new line

Instructions:

  • The input reading code is already provided
  • Replace the comment with your for loop
  • Use range(start, end, step) in your loop

Cheat sheet

The range() function can be used in three ways:

  1. range(stop): Starts from 0, ends at stop (exclusive), steps by 1
  2. range(start, stop): Starts at start (inclusive), ends at stop (exclusive), steps by 1
  3. range(start, stop, step): Starts at start, ends at stop, uses specified step

Examples:

# Counts from 0 to 4
for i in range(5):
    print(i)

# Counts from 2 to 5
for i in range(2, 6):
    print(i)

# Counts odd numbers from 1 to 9
for i in range(1, 10, 2):
    print(i)

# Counts down by 2s from 10 to 2
for i in range(10, 0, -2):
    print(i)

Remember:

  • Start is inclusive, stop is exclusive
  • Step can be positive or negative

Try it yourself

# Get input from user
start = int(input())
end = int(input())
step = int(input())

# Write your for loop here
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals