Subscribe Contact

Table of Contents  »  Chapter 4 : Repetition (a.k.a Loops)

Repetition (a.k.a Loops)

Overview

Repetition in programming allows us to repeat one or more programming statements as many times as needed to accomplish a task. Like Decisions, repetition is a very common and useful programming concept. Implementing repetition in Python involves choosing from a few repetition options in the language. Repetition operates based on conditions, like decisions. One of the repetition options is called a while loop, which repeats statements until a specified condition is met. For example, let's say we want to prompt the user for several numbers and after they have entered them we want to calculate and report the average of those numbers. We could write this task out in English something like this:

1. Ask the user to enter a number
2. Store the number they entered
3. And then repeat the following:
    a. Ask the user for the next number
    b. Add the new number entered to a running total
    c. When they are finished entering numbers stop asking for more numbers
4. Next, calculate the average by dividing the running total by the number of numbers the user entered
5. Lastly, print a message for the user informing them of the average of the numbers they entered.

This is an example of repetition, in this case, we repeat asking for the next number until they are "finished," which is our condition. We will cover this and other examples of how to use repetition in this chapter.

Chapter 4 Contents

  1. Repetition Concepts
  2. while Loop
  3. for Loop
  4. Nested Loops
  5. Validating User Input



«  Previous : Decisions : In-line if Statements
Next : Repetition : Repetition Concepts  »




© 2023 John Gordon
Cascade Street Publishing, LLC