Python: Repeating Tasks with For and While Loops
This tutorial will guide you through understanding and utilizing `for` and `while` loops in Python. These loops are fundamental to automating repetitive tasks, making your code more efficient and versatile. We’ll build three examples, starting with simple iterations and progressing to scenarios requiring conditional repetition.
1. Using a For Loop to Iterate Through a List
The `for` loop is designed to iterate over a sequence (like a list, string, or range). It automatically handles the iteration process, saving you from manually managing indices.
- Initialization: We’ll create a list of numbers and then loop through it, printing each number.
- Iteration: The `for` loop will assign each element in the list to a variable (in this case, `number`) during each iteration.
- Execution: Inside the loop, we’ll perform a simple operation (printing the number) and continue to the next element.
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
Explanation: The code iterates through the `numbers` list. In the first iteration, `number` is 1. In the second iteration, `number` is 2, and so on, until the last iteration where `number` is 5. The `print(number)` statement executes for each value of `number` in the list.
Common Mistake: Forgetting the colon (`:`) at the end of the `for` statement. This is a syntax error.
Correction: Ensure that the `for` statement ends with a colon. The example code provided does so correctly.
Math Concept: The loop executes 5 times. Each iteration performs a simple `print` operation, which doesn’t inherently involve any complex math calculations. The output is simply the repeated printing of the numbers in the list.
Output:
1
2
3
4
5
2. Using a While Loop with a Condition
The `while` loop continues to execute as long as a specified condition is true. It’s crucial to ensure the condition eventually becomes false to avoid an infinite loop.
- Initialization: We’ll initialize a counter variable.
- Condition: The `while` loop checks if the counter is less than 10.
- Increment/Decrement: Inside the loop, we’ll increment the counter in each iteration.
- Termination: The loop will stop when the counter reaches 10.
count = 0
while count < 10:
print(count)
count += 1
Explanation: The `while` loop continues to execute as long as `count` is less than 10. Inside the loop, the current value of `count` is printed and then `count` is incremented by 1. This ensures that `count` eventually becomes 10, at which point the condition `count < 10` becomes false, and the loop terminates.
Common Mistake: Forgetting to update the variable used in the condition. If the condition never becomes false, the loop will run indefinitely.
Correction: Make sure to increment or decrement the variable used in the condition within the loop’s body. The example code correctly increments `count` in each iteration.
Math Concept: The loop executes 10 times. The `count += 1` operation adds 1 to the `count` variable in each step. This is a fundamental arithmetic operation.
Output:
0
1
2
3
4
5
6
7
8
9
3. Nested For Loops – Iterating Through Multiple Lists
Nested loops allow you to iterate through multiple sequences simultaneously. This is useful for tasks like processing 2D arrays or combinations of data.
- Outer Loop: The outer loop iterates through rows of a matrix.
- Inner Loop: The inner loop iterates through columns of the same matrix.
- Calculation: Inside the inner loop, we’ll calculate the sum of each element in the matrix.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=" ") #Print each element separated by a space
print() #Move to the next line after printing each row
Explanation: The outer loop iterates through each `row` in the `matrix`. For each row, the inner loop iterates through each `element` within that row. Inside the inner loop, the current `element` is printed followed by a space. After all elements in a row have been printed, the `print()` statement moves the cursor to the next line, so that the next row can be printed correctly.
Math Concept: This example calculates the sum of all elements within the matrix. The sum is calculated by iterating through all the elements and adding them up. The sum is calculated as 1+2+3+4+5+6+7+8+9 = 45.
Output:
1 2 3
4 5 6
7 8 9



Leave a Reply