Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

5.2 For loop

Learning objectives

By the end of this section you should be able to

  • Explain the for loop construct.
  • Use a for loop to implement repeating tasks.

For loop

In Python, a container can be a range of numbers, a string of characters, or a list of values. To access objects within a container, an iterative loop can be designed to retrieve objects one at a time. A for loop iterates over all elements in a container. Ex: Iterating over a class roster and printing students' names.

Range function in for loop

A for loop can be used for iteration and counting. The range function is a common approach for implementing counting in a for loop. A range function generates a sequence of integers between the two numbers given a step size. This integer sequence is inclusive of the start and exclusive of the end of the sequence. The range function can take up to three input values. Examples are provided in the table below.

Table 5.1 Using the range function.
Range functionDescriptionExampleOutput
range(end) Generates a sequence beginning at 0 until end. Step size: 1 range(4)0, 1, 2, 3
range(start, end) Generates a sequence beginning at start until end. Step size: 1 range(0, 3)0, 1, 2
range(2, 6)2, 3, 4, 5
range(-13, -9)-13, -12, -11, -10
range(start, end, step) Generates a sequence beginning at start until end. Step size: steprange(0, 4, 1)0, 1, 2, 3
range(1, 7, 2)1, 3, 5
range(3, -2, -1)3, 2, 1, 0, -1
range(10, 0, -4)10, 6, 2