Chapter 8. Loop the Loop

 

For most people, doing the same thing over and over again is very boring, so why not let the computer do that for us? Computers never get bored, so they’re great at doing repetitive tasks. In this chapter, we’re going to see how to make the computer repeat things.

Computer programs often repeat the same steps over and over again. This is called looping. There are two main kinds of loops:

  • those that repeat a certain number of times—these are called counting loops
  • those that repeat until a certain thing happens—these are called conditional loops because they keep going until some condition is true

Counting loops

The first kind of loop is called a counting loop. You’ll also hear it called a for loop, because many languages, including Python, use the for keyword to create this kind of loop in a program.

Let’s try a program that uses a counting loop. Start a new text editor window in IDLE, using the File > New command (like we did for our first program). Then type in the program in listing 8.1.

Listing 8.1. A very simple for loop

Save it as Loop1.py and run it. (You can use the Run > Run Module menu, or the shortcut of pressing the F5 key.)

You should see something like this:

Using a counting loop

A shortcut—range()

A matter of style—loop variable names

Counting by steps

Counting without numbers

While we’re on the subject . . .

Bailing out of a loop—break and continue

What did you learn?

Test your knowledge

Try it out