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
whileloop executes a block of statements repeatedly as long as a specified test condition evaluates toTrue.A
whileloop consists of two distinct components:A condition that evaluates to a Boolean
TrueorFalsevalue.A block of statements that executes repeatedly for as long as the condition remains
True.
General syntactic format of a
whileloop:
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.

* 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`.

* 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).

* 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
whileloop consists of exactly one statement, it may be written on a single line:
while condition: statement
```
* Example:
python n = 0 while n < 10: n += 1 ```
The for Loop: A Count-Controlled Loop
The
forstatement implements a count-controlled loop specifically engineered to iterate across a sequence of data values.A
forloop iterates exactly once for each element present within a sequence.General syntactic format of a
forloop:
for variable in [val1, val2, etc]:
statements
```
* **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.

* Step-by-step iteration flow for `for num in [1, 2, 3, 4, 5]: print(num)`:
* 1st iteration: `num` is assigned ``, prints ``.
* 2nd iteration: `num` is assigned ``, prints ``.
* 3rd iteration: `num` is assigned ``, prints ``.
* 4th iteration: `num` is assigned ``, prints ``.
* 5th iteration: `num` is assigned ``, prints ``.
* 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 `` up to, but not including, `ending_limit`.
* Example: `range(5)` yields ``.
* **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 ``.
* **Three arguments** `range(starting_value, ending_limit, step_value)`:
* Increments each successive value by `step_value`.
* Example: `range(2, 10, 2)` yields ``.
* **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 ``.
* **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 `` 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.

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

* 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.

* **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:
Clock Simulator Analogy:
An analog clock operates as a nested system:
For each single advance of the hours hand, the minutes hand undergoes
advances.For each single advance of the minutes hand, the seconds hand undergoes
advances.

Logic breakdown of Clock Simulator:
Outer loop evaluates if elements remain in the
hourscollection; assigns next element tohour.Middle loop evaluates if elements remain in the
minutescollection; assigns next element tominute.Inner loop evaluates if elements remain in the
secondscollection; assigns next element tosecond.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
breakstatement causes the loop immediately enclosing it to abort and terminate execution.Program control transfers to the statement immediately following the loop body.

breakexecution example: ```python n = 0 while n < 100: print(n) if n == 5: break n += 1print(f"The loop stopped and n is {n}.") ```
Program output:
text 0 1 2 3 4 5 The loop stopped and n is 5. The continue Statement:
The
continuestatement immediately halts the current iteration of a loop.When encountered, any statements remaining beneath
continuein the loop body are bypassed, and control jumps to the evaluation of the loop's next iteration.

continueexecution example:python n = 0 while n < 10: n += 1 if n % 3 == 0: continue print(n) Program output (multiples of
are omitted):text 1 2 4 5 7 8 10 The else Clause with Loops:
Python loops can include an optional
elseblock positioned at the end of the loop construct.General syntax formats:
python while condition: statements else: statements python for variable in sequence: statements else: statements Behavioral rules of loop
elseblocks:An
elseclause in a loop is practically useful when the loop incorporates an internalbreakstatement.The statement block inside
elseexecutes exclusively if the loop completes all intended iterations normally without hitting abreakstatement.If the loop terminates due to a
breakinstruction, theelsesuite is skipped entirely.
Example where
breaktriggers (elseis 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}.") Output:
text 0 1 2 3 4 Breaking out of the loop.
Example where
breakdoes not trigger (elseexecutes):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}.") Output:
text 0 1 2 After the loop, n is 2.
Turtle Graphics: Using Loops to Draw Designs
Loops combined with the
turtlelibrary allow automated rendering of geometric polygons and complex algorithmic graphics.Drawing a Square:
Uses a count-controlled loop executing
times, traveling forwardpixels and pivoting right byper iteration:
import turtle
for x in range(4):
turtle.forward(100)
turtle.right(90)
```

* **Drawing an Octagon**:
* Uses a count-controlled loop executing `` times, advancing `` pixels and turning right by `` per iteration:
python import turtle
for x in range(8): turtle.forward(100) turtle.right(45) ```

Repeated Rotated Circles:
Draws a circular geometric mandala by repeatedly rendering a circle of radius
and pivoting left byacrossiterations:
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)
```

* **Starburst Pattern**:
* Renders a ``-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) ```
