4.3. The for
Loop¶
When we drew the square, it was quite tedious. We had to move then turn, move then turn, etc. etc. four times. If we were drawing a hexagon, or an octogon, 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. In computer science, 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 write a program that prints a greating multiple times.
Take a look at the output produced when you press the run
button.
Here’s how it works:
Line 1 is the loop header. The loop header specifies how many times the loop will run. There are three numbers used to specify how many times the loop will run, the start, stop, and step. In the above example, it starts counting at 0, stops counting when it gets to 5, and counts by 1, so the loop will run 5 times. Note that the header ends in a colon symbol. It’s easy to forget the colon, but it won’t work without it.
Line 2 is the loop body. The loop body is always indented. The indentation determines exactly what statements are “in the loop”. The loop body can contain many lines of code. The above example has just one line in the body.