Chapter 4: Repetition Structures

Introduction to Repetition Structures

  • Duplicating code to perform the same task multiple times introduces significant disadvantages:

    • It makes programs unnecessarily large.

    • It is time-consuming to write and maintain.

    • Any required correction or bug fix must be manually repeated across multiple places in the program.

  • A repetition structure causes the computer to execute an included block of code repeatedly as necessary.

  • Repetition structures fall into two broad categories:

    • Condition-controlled loop: Uses a true/false Boolean condition to dictate the number of times the loop iterates.

    • Count-controlled loop: Repeats execution a specific, predetermined number of times.

The while Loop: A Condition-Controlled Loop

  • The while loop executes a block of statements repeatedly as long as a specified test condition evaluates to True.

  • A while loop consists of two distinct components:

    • A condition that evaluates to a Boolean True or False value.

    • A block of statements that executes repeatedly for as long as the condition remains True.

  • General syntactic format of a while loop:

  while condition:
      statements
  ```
* In flowchart logic, a condition is tested within a decision diamond; if `True`, control flows to the statement block and loops back to the condition diamond; if `False`, execution branches past the loop.

![Logic of a while loop showing the conditional diamond routing to statements when True and exiting when False](https://assets.knowt.com/pdf-flow-prod/50f2345f-e150-4ea4-96de-9435be741916-figures/1.png)

* Key operational mechanics:
  * **Iteration**: Refers to one complete execution of the statement body within a loop.
  * **Pretest Loop**: The `while` loop is classified as a pretest loop because it tests its condition prior to performing an iteration.
    * If the condition evaluates to `False` from the outset, the body of the loop will never execute.
    * Pretest loops typically require preparatory actions or variable initialization prior to entering the loop structure.
  * Loop termination requires an operation inside the body that alters the evaluated variable, eventually causing the condition to become `False`.

![Flowchart for Program 4-1 demonstrating a sales commission calculation while loop](https://assets.knowt.com/pdf-flow-prod/50f2345f-e150-4ea4-96de-9435be741916-figures/2.jpg)

* Program 4-1 Flowchart Logic (Commission Calculator):
  * Step 1: Assign `'y'` to variable `keep_going`.
  * Step 2: Test condition `keep_going == 'y'`.
  * Step 3: If `True`, prompt the user to enter the amount of sales and assign it to `sales`.
  * Step 4: Prompt the user to enter the commission rate and assign it to `comm_rate`.
  * Step 5: Compute `commission = sales * comm_rate`.
  * Step 6: Display `commission`.
  * Step 7: Prompt the user: `"Do you want to calculate another commission? (Enter y for yes)"` and assign the response to `keep_going`.
  * Step 8: Return to Step 2. If `False`, terminate execution (`End`).
* **Infinite Loops**:
  * A loop that lacks a mechanism to render its condition `False` will run indefinitely.
  * An infinite loop continues executing until the host program is manually interrupted by the operating environment.
  * Infinite loops typically occur when a programmer neglects to include code inside the body that updates the loop control variable.

# Using the while Loop as a Count-Controlled Loop

* Although the `while` loop is inherently condition-controlled, it can function as a count-controlled loop when paired with a counter variable.
* A counter variable is assigned a unique value during each iteration to track the number of executions.
* A count-controlled `while` loop requires three distinct programmatic actions:
  * **Initialization**: The counter variable must be assigned an initial starting value before the loop statement begins.
  * **Comparison**: The loop header must compare the counter variable against a terminal limit value to evaluate whether another iteration should execute.
  * **Update**: The body of the loop must modify the counter variable during each iteration (typically via incrementation).

![Annotated count-controlled while loop illustrating initialization, comparison, and update steps](https://assets.knowt.com/pdf-flow-prod/50f2345f-e150-4ea4-96de-9435be741916-figures/3.jpg)

* Count-controlled `while` loop implementation:

python n = 0 # Initialization while n < 5: # Comparison print(f"Inside the loop, the value of n is {n}.") n += 1 # Update   ```

  • Single-Line while Loops:

    • When the body of a while loop consists of exactly one statement, it may be written on a single line:

  while condition: statement
&nbsp;&nbsp;```
  * Example:

python n = 0 while n < 10: n += 1   ```

The for Loop: A Count-Controlled Loop

  • The for statement implements a count-controlled loop specifically engineered to iterate across a sequence of data values.

  • A for loop iterates exactly once for each element present within a sequence.

  • General syntactic format of a for loop:

  for variable in [val1, val2, etc]:
      statements
&nbsp;&nbsp;```
* **Target Variable**: The identifier placed immediately after the keyword `for` that receives the value of the current sequence element at the start of each iteration.

![Diagram showing target variable assignment across five iterations of a for loop](https://assets.knowt.com/pdf-flow-prod/50f2345f-e150-4ea4-96de-9435be741916-figures/4.jpg)

* Step-by-step iteration flow for `for num in [1, 2, 3, 4, 5]: print(num)`:
  * 1st iteration: `num` is assigned `11`, prints `11`.
  * 2nd iteration: `num` is assigned `22`, prints `22`.
  * 3rd iteration: `num` is assigned `33`, prints `33`.
  * 4th iteration: `num` is assigned `44`, prints `44`.
  * 5th iteration: `num` is assigned `55`, prints `55`.
* The target variable can be used directly inside the loop's body for mathematical calculations, formatting, or processing tasks (such as computing the square root of each number across a sequence).

# The range Function with the for Loop

* The built-in `range()` function generates an iterable object containing a sequence of integer values.
* An iterable is an object containing a sequence of values that can be iterated across one at a time.
* Argument configurations of the `range()` function:
  * **One argument** `range(ending_limit)`:
    * Generates integers beginning at `00` up to, but not including, `ending_limit`.
    * Example: `range(5)` yields `0,1,2,3,40, 1, 2, 3, 4`.
  * **Two arguments** `range(starting_value, ending_limit)`:
    * Generates integers starting at `starting_value` up to, but not including, `ending_limit`.
    * Example: `range(1, 6)` yields `1,2,3,4,51, 2, 3, 4, 5`.
  * **Three arguments** `range(starting_value, ending_limit, step_value)`:
    * Increments each successive value by `step_value`.
    * Example: `range(2, 10, 2)` yields `2,4,6,82, 4, 6, 8`.
* **Generating Sequences from Highest to Lowest**:
  * The `range()` function produces descending sequences when the starting value exceeds the ending limit and the step argument is a negative integer.
  * Example: `range(10, 0, -1)` yields the sequence `10,9,8,7,6,5,4,3,2,110, 9, 8, 7, 6, 5, 4, 3, 2, 1`.
* **User-Controlled Loop Iterations**:
  * When execution bounds are not hardcoded, loop bounds can be populated by reading inputs from the user, assigning them to variables, and passing those variables into `range()`.
  * Boundary edge cases must account for the fact that `range()` excludes the specified upper limit.

# Calculating a Running Total and Augmented Assignment Operators

* Calculating a running total requires accumulating numerical values over successive loop iterations.
* Architecture of a running total program:
  * An **accumulator variable**: Initialized to `00` outside and before the loop begins to store the cumulative sum.
  * A **repetition structure**: Iteratively reads each successive data value and adds it to the accumulator variable.
  * Upon loop termination, the accumulator holds the final calculated total.

![Flowchart illustrating running total logic including accumulator initialization and reading values](https://assets.knowt.com/pdf-flow-prod/50f2345f-e150-4ea4-96de-9435be741916-figures/5.png)

* **Augmented Assignment Operators**:
  * Shorthand assignment operators designed for statements where a variable appears on both the left and right sides of the assignment operator (`=`).

![Table 4-2 showing Python augmented assignment operators, example usage, and equivalent longhand statements](https://assets.knowt.com/pdf-flow-prod/50f2345f-e150-4ea4-96de-9435be741916-figures/14.png)

* Syntax and behavioral equivalents:
  * `+=` : `x += 5` is equivalent to `x = x + 5`
  * `-=` : `y -= 2` is equivalent to `y = y - 2`
  * `*=` : `z *= 10` is equivalent to `z = z * 10`
  * `/=` : `a /= b` is equivalent to `a = a / b`
  * `%=` : `c %= 3` is equivalent to `c = c % 3`

# Sentinels

* A sentinel is a distinctive, predefined value used to denote the termination of a sequence of data entries.
* Operating characteristics of sentinels:
  * When a program reads the sentinel value, the loop terminates immediately without processing the sentinel as regular data.
  * A sentinel value must be distinct and non-valid within normal execution domains to avoid accidental premature loop termination.
  * Example: When reading records sequentially from an input file, an empty string (`""`) or empty line serves as a sentinel indicating the end of the file.

# Input Validation Loops

* Programs cannot inherently distinguish valid input from flawed input; invalid input produces invalid calculations or errors, adhering to the principle of **GIGO** (Garbage In, Garbage Out).
* Input validation refers to the systematic practice of inspecting data for validity prior to computational execution.
* Standard input validation structures use a `while` loop that tests input criteria:
  * If input is invalid, an error message displays and the user is re-prompted to submit new data.
  * If input is valid, the loop terminates and normal processing resumes.

![Flowchart showing input validation logic prompting input, testing validity, displaying errors, and re-reading](https://assets.knowt.com/pdf-flow-prod/50f2345f-e150-4ea4-96de-9435be741916-figures/6.png)

* **The Walrus Operator (`:=`) in Input Validation**:
  * The walrus operator (`:=`) enables assignment expressions that unify the initial input read (priming read) directly inside the loop's conditional evaluation.
  * Implementation example:

python while (score := int(input("Enter your score: "))) < 0: print("The score cannot be negative.")   ```

Nested Loops

  • A nested loop is defined as a loop structure situated entirely inside the body of another loop structure.

  • General execution characteristics:

    • The inner loop performs all of its iterations for each single iteration performed by the outer loop.

    • Inner loops cycle through their iterations significantly faster than their enclosing outer loops.

    • The aggregate number of iterations executed within a nested loop system is computed using the multiplication principle:     Total iterations=(iterations of inner loop)×(iterations of outer loop)\text{Total iterations} = (\text{iterations of inner loop}) \times (\text{iterations of outer loop})

  • Clock Simulator Analogy:

    • An analog clock operates as a nested system:

    • For each single advance of the hours hand, the minutes hand undergoes 1212 advances.

    • For each single advance of the minutes hand, the seconds hand undergoes 6060 advances.

Flowchart for clock simulator utilizing nested loops for hours, minutes, and seconds
  • Logic breakdown of Clock Simulator:

    • Outer loop evaluates if elements remain in the hours collection; assigns next element to hour.

    • Middle loop evaluates if elements remain in the minutes collection; assigns next element to minute.

    • Inner loop evaluates if elements remain in the seconds collection; assigns next element to second.

    • The body prints print(hours, minutes, seconds) and cycles through all seconds before incrementing minutes, and cycles through all minutes before incrementing hours.

Loop Control Statements: break, continue, and the else Clause

  • The break Statement:

    • Execution of a break statement causes the loop immediately enclosing it to abort and terminate execution.

    • Program control transfers to the statement immediately following the loop body.

Code example highlighting the break statement terminating execution when n equals 5
  • break execution example: ```python n = 0 while n < 100: print(n) if n == 5: break n += 1

    print(f"The loop stopped and n is {n}.")     ```

  • Program output: text 0 1 2 3 4 5 The loop stopped and n is 5. &nbsp;&nbsp;&nbsp;&nbsp;

    • The continue Statement:

  • The continue statement immediately halts the current iteration of a loop.

  • When encountered, any statements remaining beneath continue in the loop body are bypassed, and control jumps to the evaluation of the loop's next iteration.

Code example illustrating the continue statement skipping iterations where n modulo 3 equals 0
  • continue execution example: python n = 0 while n < 10: n += 1 if n % 3 == 0: continue print(n) &nbsp;&nbsp;&nbsp;&nbsp;

  • Program output (multiples of 33 are omitted): text 1 2 4 5 7 8 10 &nbsp;&nbsp;&nbsp;&nbsp;

    • The else Clause with Loops:

  • Python loops can include an optional else block positioned at the end of the loop construct.

  • General syntax formats: python while condition: statements else: statements &nbsp;&nbsp;&nbsp;&nbsp;python for variable in sequence: statements else: statements &nbsp;&nbsp;&nbsp;&nbsp;

  • Behavioral rules of loop else blocks:

    • An else clause in a loop is practically useful when the loop incorporates an internal break statement.

    • The statement block inside else executes exclusively if the loop completes all intended iterations normally without hitting a break statement.

    • If the loop terminates due to a break instruction, the else suite is skipped entirely.

  • Example where break triggers (else is bypassed): python for n in range(10): if n == 5: print("Breaking out of the loop.") break print(n) else: print(f"After the loop, n is {n}.") &nbsp;&nbsp;&nbsp;&nbsp;

    • Output: text 0 1 2 3 4 Breaking out of the loop. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Example where break does not trigger (else executes): python for n in range(3): if n == 5: print("Breaking out of the loop.") break print(n) else: print(f"After the loop, n is {n}.") &nbsp;&nbsp;&nbsp;&nbsp;

    • Output: text 0 1 2 After the loop, n is 2. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Turtle Graphics: Using Loops to Draw Designs

  • Loops combined with the turtle library allow automated rendering of geometric polygons and complex algorithmic graphics.

  • Drawing a Square:

    • Uses a count-controlled loop executing 44 times, traveling forward 100100 pixels and pivoting right by 90∘90^{\circ} per iteration:

  import turtle

  for x in range(4):
      turtle.forward(100)
      turtle.right(90)
&nbsp;&nbsp;```

![A square drawn using a 4-iteration turtle graphics loop](https://assets.knowt.com/pdf-flow-prod/50f2345f-e150-4ea4-96de-9435be741916-figures/10.png)

* **Drawing an Octagon**:
  * Uses a count-controlled loop executing `88` times, advancing `100100` pixels and turning right by `45∘45^{\circ}` per iteration:

python import turtle

for x in range(8): turtle.forward(100) turtle.right(45)   ```

An octagon drawn using an 8-iteration turtle graphics loop
  • Repeated Rotated Circles:

    • Draws a circular geometric mandala by repeatedly rendering a circle of radius 100100 and pivoting left by 10∘10^{\circ} across 3636 iterations:

  import turtle

  NUM_CIRCLES = 36  # Number of circles to draw
  RADIUS = 100  # Radius of each circle
  ANGLE = 10  # Angle to turn

  for x in range(NUM_CIRCLES):
      turtle.circle(RADIUS)
      turtle.left(ANGLE)
&nbsp;&nbsp;```

![Geometric circular rosette pattern created by rotating circles across 36 iterations](https://assets.knowt.com/pdf-flow-prod/50f2345f-e150-4ea4-96de-9435be741916-figures/12.png)

* **Starburst Pattern**:
  * Renders a `3636`-line radiating starburst design by moving the turtle coordinate system, lowering the pen, and cycling through forward traversals and turns:

python import turtle

START_X = -200 # Starting X coordinate START_Y = 0 # Starting Y coordinate NUM_LINES = 36 # Number of lines to draw LINE_LENGTH = 400 # Length of each line ANGLE = 170 # Angle to turn

turtle.hideturtle() turtle.penup() turtle.goto(START_X, START_Y) turtle.pendown()

for x in range(NUM_LINES): turtle.forward(LINE_LENGTH) turtle.left(ANGLE)   ```

Starburst design constructed with 36 straight lines turned at 170 degree intervals