Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Loops

Now we turn to loops, which are used to repeatedly execute blocks of code. Python has two main kinds of loops: for-loops and while-loops. For-loops are generally easier to use and less error prone than while-loops, although not quite as flexible.

For-loops

The basic for-loop repeats a given block of code some specified number of times. For example, this snippet of code prints the numbers 0 to 9 on the screen:

# count10.py
for i in range(10):
    print(i)

The first line of a for-loop is called the for-loop header. A for-loop always begins with the keyword for. After that comes the loop variable, in this case i. Next is the keyword in, typically (but not always) followed by range(n) and a terminating : token. A for-loop repeats its body, the code block underneath it, exactly n times.

Each time the loop executes, the loop variable i is set to be the next value. By default, the initial value of i is 0, and it goes up to n - 1 (not n!) by ones. Starting numbering at 0 is fairly common in programming, although it is surprising at first.

If you want to change the starting value of the loop, add a starting value to range:

for i in range(5, 10):
    print(i)

This prints the numbers from 5 to 9.

Thinking about for-loops as printing a list of numbers is a good way to learn what they do. We will see many more examples of for-loops throughout this book.

While-loops

The second kind of Python loop is a while-loop. Consider this program:

# while10.py
i = 0
while i < 10:
    print(i)
    i = i + 1  # add 1 to i

This prints out the numbers from 0 to 9 on the screen. It is noticeably more complicated than a for-loop, but it is also more flexible.

The while-loop itself begins on the line beginning with the keyword while; this line is called the while-loop header, and the indented code underneath it is called the while-loop body. The header always starts with while and is followed by the while-loop condition. This condition is a Boolean expression that returns True or False.

The flow of control through a while-loop goes like this: First, Python checks if the loop condition is True or False. If it’s True, it executes the body; if it’s False, it skips over the body (that is, it jumps out of the loop) and runs whatever statements appear afterward. When the condition is True, the body is executed, and then Python checks the condition again. As long as the loop condition is True, Python keeps executing the loop. Figure 4.2 shows a flow chart for this program.

Figure 4.2

Figure 4.2 This is a flow chart for code that counts from 0 to 9. Notice that when the loop condition is False (that is, the no branch is taken in the decision box), the arrow does not go into a box. That’s because in our sample code there is nothing after the while-loop.

The very first line of the sample program is i = 0, and in the context of a loop it is known as an initialization statement, or an initializer. Unlike with for-loops, which automatically initialize their loop variable, it is the programmer’s responsibility to give initial values to any variables used by a while-loop.

The last line of the loop body is i = i + 1. As it says in the source code comment, this line causes i to be incremented by 1. Thus, i increases as the loop executes, which guarantees that the loop will eventually stop. In the context of a while-loop, this line is called an increment, or incrementer, since its job is to increment the loop variable.

The general form of a while-loop is shown in the flow chart of Figure 4.3.

Figure 4.3

Figure 4.3 A flow chart for the general form of a while-loop. Note that the incrementer is not shown explicitly: It is embedded somewhere in body_block often (but not always) at the end of that block.

Even though almost all while-loops need an initializer and an incrementer, Python does not require that you include them. It is entirely up to you, the programmer, to remember these lines. Even experienced programmers find that while-loop initializers and incrementers are a common source of errors.

  • + Share This
  • 🔖 Save To Your Account