What is Iteration?
When we talk about iteration in Python, we're talking about repeating actions repeatedly. Let's explore two main ways to do this: `for` loops and `while` loops.
Baisc Loop Types
Loop Type | Description | Example |
---|---|---|
For Loop | A standard loop used to iterate over a sequence (like a list, tuple, or range) or numbers. Important Note: The range starts at 0 and stops at 5 (does not include 5). |
|
Enhanced For Loop | A type of for loop used to simplify iterating over elements in a list |
|
While Loop | A loop that runs as long as a specified condition is true. |
|
When to Use a For Loop vs. While Loop
Use a
for
loop when:You know how many times you need to repeat an action.
You want to iterate over a list (Ex. fruits = [“apple“, “banana”, “cherry“]
Use a
while
loop when:The number of iterations is unknown and depends on a condition
Examples:
Continuously asking the user for input until they provide a valid answer.
Common Errors in Loops
Below are a couple mistakes you might encounter while working with for and while loops, along with code examples to illustrate them.
Infinite Loop in a While Loop
One of the most common errors when using a while
loop is creating an infinite loop. This happens when the condition of the loop never becomes false, causing the loop to run indefinitely.
# Infinite loop because the condition is always true
count = 0
while count < 5:
print(count)
# Forgot to update the count variable, so the condition is never false
Mini Challenge
Download the starter file here.
Write a program that:
Uses a
for
loop to iterate through the numbers 1 to 10 and prints whether each number is even or odd.Uses an enhanced
for
loop to iterate through a list of names and prints each nameUses a
while
loop to continuously ask the user to guess a secret number (between 1 and 5). If the user guesses incorrectly, the loop should continue until the user guesses the correct number.
Off-by-One Error in For Loop
Another common mistake with for loops is the "off-by-one" error, where the loop runs one extra or one fewer time than expected. This typically happens when you're working with ranges or lists and miscalculate the bounds.
# Off-by-one error because range(5) gives numbers from 1 to 4, but the user expects 1 to 5
for i in range(1, 5):
print(i)