Subscribe Contact

Home  »  Chapter 4 : Repetition
for Loops

Overview

On the previous page, I introduced you to the while loop and explained that it is a condition-controlled repetition structure. The while loop is a good choice when we want to repeat (iterate) statements based on a condition we can test. The for loop is different.

Concept: Iterable

An object that is used as a sequence of elements. It is also referred to as a container that can various data elements.

The for loop is a count-controlled repetition structure that iterates a specific number of times. There are several ways in which we can define the number of times a for loop will repeat, usually based on a sequence or range of values. I will describe them briefly first, then look closely at one of them in detail, then we will see more of them in detail as we proceed through this book.

General Form

The general form of the code and flowchart representation of the for loop is as follows:

for variable in [val_1, val_2, ... val_n]:
statement_1
statement_2
.
.
statement_n
Code Details:
  • The variable in the for statement controls access to the iterable contained inside the brackets [ ].
  • Inside the loop statements, we often refer to the variable in calculations, printing, etc. Each time the loop iterates that value will change so inside the loop we can take advantage of the iteration changing the value for our purposes.
  • The iterable may be a range of numbers, a string, a list, etc. (we'll learn more about various types of iterable structures later).
  • The in keyword is the operator between the variable and the iterable.
  • The statements are executed for each element in the iterable until it runs out of elements.
Flowchart Details:
  • The execution path includes any code before the for statement.
  • The for loop signature is represented by the diamond shape which checks if there are still items in the iterable at each repetition.
  • For each iteration, when there is another element, execution enters the loop and the Statement(s) are executed each time the loop repeats.
  • Execution remains in the loop until there are no more elements in the iterable.
  • When there are no more elements in the iterable, execution exits the loop and continues to the next statement after the loop.


range() Function

Before we look at some examples, let's take a look at the Python range() function. The range() function returns a sequence of numbers based on start, stop and step (increment) values we specify. Here is the general form of the range() function:

range(start, stop, step)

The first important detail to know about the range() function is that by default ranges of values start with zero (0). This is important to keep in mind because when counting, ranges do not count 1, 2, 3, ... n, instead they count 0, 1, 2 ... (n-1). So if I want a range of 5 numbers, those numbers would be 0, 1, 2, 3, 4 not 1, 2, 3, 4, 5. We can adjust for this using the parameters of the range function.

The range() function works with the following parameters: start (optional) which indicates what number you want the range to start with, stop (required) indicates what number to end with and step (optional) which controls how many numbers to increment by on each iteration.

We can call the range() function several ways:

range(stop) which returns a range of numbers from zero (0) to the value of stop. Example: range(5) returns 0, 1, 2, 3, 4. We could read this range statement as "give me a range of integers from 0 to 5".

range(start, stop) which returns a range of numbers from the value of start to the value of stop. Example: range(1, 5) returns 1, 2, 3, 4. Notice that the last digit in the sequence is 4, not 5. We could read this range statement as "give me a range of integers from 1 to 5".

range(start, stop, step) which returns a range of numbers from the value of start to the value of stop, with an interval between start and stop of step. Example: range(2, 20, 2) returns 2, 4, 6, 8, 10, 12, 14, 16, 18. We could read this range statement as "give me a range of integers from 2 to 20 in steps of 2".

Examples
Now let's combine the for loop with the range() function in some examples.

Code Example Output Notes
for x in (range(5)):
    print(x)
0
1
2
3
4
Prints a range with only the stop parameter.
for x in (range(10, 15)):
    print(x)
10
11
12
13
14
Prints a range with the start and stop parameters.
for x in (range(10, 100, 10)):
    print(x)
10
20
30
40
50
60
70
80
90
Prints a range with the start, stop and step parameters. Note that this produces a list of the tens from ten (start) to 100 (stop). The step parameters control the interval between each iteration of the loop.
for x in (range(0, 100, 10)):
    print(x)
0
10
20
30
40
50
60
70
80
90
Prints the same range as the previous example above, except that we get 0 in the output when we set start to 0.
for x in (range(5, 50, 5)):
    print(x)
5
10
15
20
25
30
35
40
45
Print a range from 5 to 50, by fives. Notice the pattern here when we set our start and step to the same number.


There are many other ways we can use for loops. We will explore these as we proceed through the ebook. For now, try out the following practice problems.

Tracing Loop Execution

When you are learning programming structures, especially those that repeat steps, it is often very useful to manually trace the execution of that structure. For loops this is called loop tracing. When we trace code execution it is important to, first, understand how the structure works and, second, to write out each step the way the interpreter will execute each step in the computer.

For example, consider the following for loop:

for i in range(5):
    print(i)
To trace this loop, we must be aware that the range() function provides the number of iterations the loop will make. In this example, this for loop will iterate 5 times. We also must be aware that range values start at zero, so the values that the variable i will contain during the execution of this code will be 0, 1, 2, 3, and 4.

Execution Trace Table

Iteration i i < 5 print(i)
1 0 True 0
2 1 True 1
3 2 True 2
4 3 True 3
5 4 True 4
6 5 False Exit loop
Execution Trace Notes:
  • During the first iteration, i will equal 0 (the start of the range() function values). When the for loop signature is evaluated it will evaluate to True because i (0) is less than the range value of 5. And the print() function will print the value of i, which in this first iteration is zero.
  • The second thru fifth iterations will follow the same logic, the value of i is set by the range() function and each time the value of i will be less than the range() value. So, for each iteration the print() function will print the value of i.
  • In the last iteration, the value of i will reach 5, which is not less than 5, so the loop will exit and printing will stop.
  • The resulting output will be the numbers zero thru 4.

Practice Problems

Problem 1

Write a Python program that uses a for loop and the range() function to print numbers from zero to 13 (including 13) using only one parameter in the range() function.



Problem 2

Write a Python program that uses a for loop and the range() function to print numbers from 11 to 20 (not including 20).



Problem 3

Write a Python program that uses a for loop and the range() function to print the numbers between 40 and 80 (inclusive) that are divisible by 4.



Problem 4

Write a Python program that prompts the user for the start, stop and step values for a for loop based on the range() function. Here's an example of the output from a possible solution. Notice the details of the user instructions, prompts, and the output statement contains the values they entered as part of the output statement for the user.

--------------------------------------------------
Enter integers for the following loop parameters:

Start: 10000
Stop: 10100
Step: 10
--------------------------------------------------
Here is your range(10000, 10100, 10) output:
--------------------------------------------------
10000
10010
10020
10030
10040
10050
10060
10070
10080
10090




 


«  Previous : Repetition : while Loops
Next : Repetition : Nested Loops  »



© 2023 John Gordon
Cascade Street Publishing, LLC