Python for Loop with Range

Summary: in this tutorial, you’ll learn about the Python for loop and how to use it to execute a code block a fixed number of times.

Introduction to Python for loop statement with the range() function #

In programming, you often want to execute a block of code multiple times. To do so, you use a for loop.

The following illustrates the syntax of a for loop:

for index in range(n):
    statementCode language: Python (python)

In this syntax, the index is called a loop counter. And n is the number of times that the loop will execute the statement.

The name of the loop counter doesn’t have to be index, you can use whatever name you want.

The range() is a built-in function in Python. It’s like the print() function in the sense that it’s always available in the program.

The range(n) generates a sequence of n integers starting at zero. It increases the value by one until it reaches n.

So the range(n) generates a sequence of numbers: 0,1, 2, …n-1. Note that it’s always short of the final number (n).

The following diagram illustrates the for loop statement: