Skip to main content

Section 5.1 What is Iteration?

Way back in Section 1.8 we talked about the basic components of most programs:
  • input
  • output
  • math and logic
  • conditional execution
  • repetition
You have seen and written programs using all these components except for repetition. Now it’s time to learn about that.
Here’s a program that prints the squares and cubes of the numbers 1 through 5.
That looks like repetition, but it’s really mostly retyping. Let’s rewrite the code to use a variable. That way we can use copy and paste to do our repetition:
As you see, there is a lot of repetition in this program. Can you imagine what the program would look like if we wanted the table for the numbers 1 through 25? And what if we wanted to ask the user how many entries they wanted in the table? There would be no way to write that program with copy and paste, because we wouldn’t know how many times to copy and paste until the user told us! There must be a better way.
We call the process of repeating some section of code iteration, and it is something that computers do well. Because iteration is so common, Python provides several language features to make it easier. Let’s investigate some of these features.