Lecture 2b
Iteration
Iteration is the process of repeating a block of code multiple times.
Iteration helps to avoid repetitive code and efficiently execute tasks.
while Loop
A while loop repeats a block of code as long as a given condition is true.
Syntax:
The code inside the loop will execute as long as <condition> evaluates to True.
Once the code inside the loop has executed, the <condition> is checked again. If it is still True, the code will execute again. This process continues until the <condition> is False.
If the <condition> is False at the start, the code inside the loop will never execute.
Common uses:
Validating user input: repeatedly asking for input until a valid input is provided.
Repeating a task a specific number of times using a counter variable.
Performing calculations until a specific condition is met.
Loop: Counter Variables
Counter variables are frequently used to control the number of iterations in a while loop.
They keep track of the current iteration and are updated within the loop.
Example:
Shorthand operators like += can be used for updating counters.
Loop: Common Mistakes
Forgetting to update the counter variable: This can lead to an infinite loop, where the loop continues indefinitely.
"Off-by-one" errors: These occur when the loop iterates one time too many or one time too few.
Interrupting a Program
If a program gets stuck in an infinite loop, you can stop it by clicking the red square in Spyder.
for Loop
A for loop iterates over a sequence (such as a string or a range of numbers).
Syntax:
In each iteration, the <loop variable> is assigned to the next object in the <sequence>, and the code inside the loop is executed.
This process continues until all objects in the <sequence> have been processed.
Common uses:
Iterating over characters in a string.
Repeating a task a specific number of times using range().
Processing elements in data structures like lists (covered later in the course).
Loop with Strings
Strings can be used as sequences in for loops because they are a sequence of characters (or more accurately, Unicode code points).
Example:
Loop: Naming Loop Variables
Loop variables should follow naming conventions (using snake_case) and have meaningful names for readability.
Common conventions:
Use i (or j, k for nested loops) for indices (0, 1, 2, ...).
Use r, c for row and column indices.
Use ch, char, letter when the sequence is a string.
Use _ if the loop variable is not used inside the loop.
Loop with
range(n) generates a sequence of integers: 0, 1, ..., n-1 (not including n).
Example:
vs Loops
Feature for loop while loop | ||
Sequence/Condition | Uses a sequence. | Uses a condition. |
Number of Iterations | Number of iterations is usually known in advance (unless the sequence size changes during the loop). | Number of iterations may be unknown and can be unbounded (potentially leading to infinite loops if the condition never becomes false). |
Rewriting | Can often be rewritten as a while loop. | May not always be easily rewritten as a for loop. |
Choosing the Right Loop
Rule of thumb: Use a for loop in the following cases:
The number of iterations is known.
You are iterating over a sequence (like a string or range()).
The while loop logic can be easily converted to a for loop structure.
Nested Loops
Loops can be nested inside one another, creating nested loops.
The innermost loop is the loop that is nested at the deepest level.
Accumulators
Accumulators are variables used to store and update values within a loop.
They are often used to calculate sums, products, or other cumulative results.