7.2. The for Loop

Back when we drew the images with turtle it could be quite tedious. If we wanted to draw a square then we had to move then turn, move then turn, etc. etc. four times. If we were drawing a hexagon, or an octagon, or a polygon with 42 sides, it would have been a nightmare to duplicate all that code.

A basic building block of all programs is to be able to repeat some code over and over again. We refer to this repetitive idea as iteration. In this section, we will explore some mechanisms for basic iteration.

In Python, the for statement allows us to write programs that implement iteration. As a simple example, let’s say we have some friends, and we’d like to send them each an email inviting them to our party. We don’t quite know how to send email yet, so for the moment we’ll just print a message for each friend.

Take a look at the output produced when you press the run button. There is one line printed for each friend. Here’s how it works:

The overall syntax is for <loop_var_name> in <sequence>:

You have attempted of activities on this page