Lesson 16 of 4040%

(Progress persistence is disabled until Phase 9)

Python
Beginner

range()

Generate sequences of numbers for looping.

The range() Function

What You’ll Learn

You’ll learn how to loop a specific number of times using the range() function.

Looping X Times

To loop through a set of code a specified number of times, we can use the range() function. It returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

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

Expected Output:

0
1
2
3
4

(Notice it starts at 0 and goes up to, but does not include, 5)

Specifying a Start Value

You can add a start parameter by passing two arguments: range(start, end).

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

Expected Output:

2
3
4
5

Specifying a Step Value

You can specify how much to increment by adding a third argument: range(start, end, step).

for x in range(0, 10, 2):
    print(x)

Expected Output:

0
2
4
6
8

Lesson Progress

Take QuizBuild a Python Project