4.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.

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 out to the console to imitate the idea of emailing 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