JK

Repetition Structures in Python

Introduction to Repetition Structures

  • Often, code needs to perform the same task multiple times. This can lead to:
    • Code Duplication Disadvantages:
    • Makes program larger.
    • Costly in time and effort.
    • Errors may need correction in multiple code locations.
  • Repetition Structures: allow the computer to repeat sections of code as necessary. They include:
    • Condition-Controlled Loops (e.g., while loop)
    • Count-Controlled Loops (e.g., for loop)

The while Loop: a Condition-Controlled Loop

  • Nature of while Loop:

    • Executes as long as a specified condition is true.
    • Components:
    • Condition: evaluated for true/false.
    • Statements: executed whenever the condition is true.
    • General Format:
      while condition:
      statements
  • How while Loop Works:

    • Iteration: One execution of the loop's body.
    • It is a pretest loop, meaning the condition is checked before each iteration.
    • If the condition is false from the start, no execution will occur.
    • Inside the loop, the condition must eventually become false.
  • Infinite Loops:

    • A loop with no termination condition becomes an infinite loop, repeating indefinitely until interrupted.
    • This often occurs when a programmer forgets to include stopping conditions.

The for Loop: a Count-Controlled Loop

  • Nature of for Loop:

    • A count-controlled loop runs a specific number of iterations.
    • Uses a for statement designed for sequences of data items.
    • General Format:
      for variable in [val1, val2, ...]:
      statements
  • Using the range Function:

    • Simplifies the creation of a for loop.
    • Characteristics of range Function:
    • One argument: defines the end limit.
    • Two arguments: defines starting value and end limit.
    • Three arguments: adds a step value.
  • Controlling Loop Iterations with User Input:

    • Variable inputs can determine the number of iterations before calling range().
    • Always note that the ending limit is not included in the range.
  • Generating Descending Sequences with range:

    • Example: range(10, 0, -1) generates numbers from 10 to 1.

Calculating a Running Total

  • Purpose:
    • Programs need to calculate totals from a series of numbers.
    • Consists of two elements:
    1. A loop to read each number.
    2. An accumulator variable that maintains the running total.
    • At the end of the loop, the accumulator reflects the total amount.

The Augmented Assignment Operators

  • Definition:
    • These operators simplify assignment statements where the variable appears on both sides of the operation.
  • Examples:
    • += : x += 5 means x = x + 5
    • -= : y -= 2 means y = y - 2
    • *= : z *= 10 means z = z * 10
    • Other operators include /=, %=, //=, **=.

Sentinels

  • Definition:
    • A sentinel is a unique value indicating the end of a sequence of inputs.
    • When reached, the loop can terminate, avoiding misinterpretation of regular values.
    • Example: An empty line can act as a sentinel when processing input files.

Input Validation Loops

  • Importance:
    • Computers cannot inherently differentiate between valid and invalid data.
    • Bad input leads to bad output (GIGO: garbage in, garbage out).
  • Input Validation Process:
    • Verify input validity before processing.
    • A while loop can ensure only valid data is accepted:
    • If data is invalid, prompt for correct input, and repeat.
    • If valid, process the input accordingly.

Nested Loops

  • Definition:
    • A nested loop exists within another loop, where the inner loop executes fully for each iteration of the outer loop.
    • Example: An analog clock where the hour hand depends on the minute hand, and seconds depend on minutes.
  • Key Points:
    • Inner loops complete quicker than outer loops.
    • Total iterations equal: (iterations of inner loop) x (iterations of outer loop).

Summary

  • This chapter covered:
    • Repetition structures: condition-controlled and count-controlled loops, including nested loops.
    • Techniques to avoid infinite loops and use the range function within for loops.
    • Calculating running totals, employing augmented assignment operators, and utilizing sentinels for ending sequences effectively.