Loops and Iteration

Loops and Iteration

Repeated Steps

  • Loops involve repeated steps with iteration variables that change during each loop.
  • Iteration variables often go through a sequence of numbers.

Infinite Loop

  • An infinite loop occurs when the condition controlling the loop never becomes false, causing the loop to execute indefinitely.

Breaking Out of a Loop

  • The break statement ends the current loop and jumps to the statement immediately following the loop.

Finishing an Iteration with Continue

  • The continue statement ends the current iteration and jumps to the top of the loop, starting the next iteration.

Indefinite Loops

  • While loops are called "indefinite loops" because they continue until a logical condition becomes false.

Definite Loops

  • For loops are called "definite loops" because they execute an exact number of times, iterating through the members of a set.

A Simple Definite Loop

  • Example: for i in [5, 4, 3, 2, 1] : print i

Looking at In…

  • The iteration variable “iterates” through the sequence (ordered set).
  • The block (body) of code is executed once for each value in the sequence.
  • The iteration variable moves through all of the values in the sequence.

Counting in a Loop

  • To count how many times a loop executes, use a counter variable, initialized at 0, and increment it each time through the loop.

Summing in a Loop

  • To add up values in a loop, use a sum variable, initialized at 0, and add the current value to it each time through the loop.

Finding the Average in a Loop

  • Combine counting and summing patterns, and divide the total by the count after the loop completes to find the average.

Filtering in a Loop

  • Use an if statement within the loop to filter values based on a condition.

Search Using a Boolean Variable

  • Use a boolean variable to track whether a value has been found during the loop.

Finding the Smallest Value

  • Keep track of the smallest value found so far during the loop.

The "is" and "is not" Operators

  • Python has an "is" operator that can be used in logical expressions.
  • Implies 'is the same as'
  • Similar to, but stronger than ==
  • 'is not' is also a logical operator