Python For Loop Range

In this tutorial, we will learn how to use range() function with Python For Loop.

range object is an iterable with sequence of integers. And for loop can iterate over a range object.

Following is the syntax of for loop using range() function.

</>
Copy
for index in <range> :
    statement(s)

Following is the syntax of range() function.

</>
Copy
range(start, stop[, step])

range() function returns an object that generates a sequence of integers. These integers range from from start (inclusive) to stop (exclusive) with adjacent integers separated by step. range(i, j) produces i, i+1, i+2, …, j-1. For example, range(2, 20, 3) means 2, 5, 8, 11, 14, 17.

start has a default value of 0. And you can just provide stop as argument to range() function. So range(4) means a sequence of integers 0, 1, 2, 3.

Example 1 – Python For Loop Range

In this example, we will use range() function, to iterate over integers from 0 to 8.

Python Program

</>
Copy
for i in range(9) :
    print(i)

Output

0
1
2
3
4
5
6
7
8

Example 2 – Python For Loop with Range having a Different Start

In this example, we will use range() function, to iterate over integers from 4 to 8.

Python Program

</>
Copy
for i in range(4, 9) :
    print(i)

Output

4
5
6
7
8

Example 3 – Python For Loop with Range having a Different Steps

In this example, we will use range() function, to iterate over integers from 2 up to 20 insteps of 3.

Python Program

</>
Copy
for i in range(2, 20, 3) :
    print(i)

Output

2
5
8
11
14
17

Conclusion

Concluding this Python Tutorial, we learned how to use Python For Loop with a Range object.