Python: Repeat Tasks with For and While Loops
This tutorial demonstrates how to use `for` and `while` loops in Python to repeat tasks. We’ll cover the fundamentals of each loop type with practical examples. Understanding loops is crucial for automating repetitive operations and creating dynamic programs.
For Loops
The `for` loop is used to iterate over a sequence (like a list, string, or range). It’s ideal when you know in advance how many times you want to repeat a block of code.
Example 1: Printing Numbers from 1 to 5
Let’s create a simple program to print the numbers from 1 to 5 using a `for` loop and the `range()` function.
# Import the range function
range = range
# Iterate from 1 to 5 (inclusive)
for i in range(1, 6):
print(i)
Explanation:
- `range(1, 6)` generates a sequence of numbers from 1 up to (but not including) 6. So, it produces the numbers 1, 2, 3, 4, and 5.
- The `for` loop iterates through this sequence, assigning each number to the variable `i` in each iteration.
- Inside the loop, `print(i)` prints the current value of `i` to the console.
Input: None
Intermediate Values: i takes values 1, 2, 3, 4, 5
Output:
1
2
3
4
5
Example 2: Iterating Through a List
Now, let’s iterate through a list of strings.
# Create a list of strings
fruits = ["apple", "banana", "cherry"]
# Iterate through the list
for fruit in fruits:
print(fruit)
Explanation:
- We initialize a list named `fruits` containing three string elements.
- The `for` loop iterates through each element in the `fruits` list, assigning each element to the variable `fruit` in each iteration.
- `print(fruit)` prints the current value of `fruit` to the console.
Input: None
Intermediate Values: fruit takes values “apple”, “banana”, “cherry”
Output:
apple
banana
cherry
While Loops
The `while` loop executes a block of code as long as a specified condition is true. Unlike the `for` loop, it doesn’t automatically iterate over a sequence; you control when the loop stops.
Example 3: Counting Down from 5
Let’s create a program that counts down from 5 to 1 using a `while` loop.
# Initialize the counter
count = 5
# While the counter is greater than 0
while count > 0:
print(count)
count -= 1 # Decrement the counter
Explanation:
- We initialize a variable `count` to 5.
- The `while` loop continues as long as `count` is greater than 0.
- Inside the loop:
- `print(count)` prints the current value of `count`.
- `count -= 1` decrements `count` by 1 in each iteration. This is crucial to avoid an infinite loop.
Input: None
Intermediate Values: count takes values 5, 4, 3, 2, 1
Output:
5
4
3
2
1
Common Mistakes:
- Infinite Loops: If the condition in the `while` loop never becomes false, the loop will run forever. Make sure your loop’s condition eventually evaluates to `False`.
- Incorrect Updates: Ensure that the variables used in the loop’s condition are updated correctly within the loop’s body.



Leave a Reply