Python Loops & Iterations: Master For, While and Else Clauses

Introduction to Python Loops
In programming, we follow the DRY (Don't Repeat Yourself) principle. Instead of writing the same code multiple times, we use Loops to automate repetitive tasks.
A loop allows you to execute a block of code multiple times by iterating over a sequence (like a list, dictionary, or string) or until a specific condition is met.
The Golden Rule of Loops
Every loop must have a terminating condition. Without one, you create an 'infinite loop' that can crash your program!
1. The Python for Loop
The for loop is used when you want to iterate over a sequence. It is the most common way to access every element in a collection.
Syntax
1for item in sequence:
2 # Code to execute for each itemExample: Iterating over a List
1fruits = ['Apple', 'Banana', 'Cherry']
2for fruit in fruits:
3 print(f"I love {fruit}")Example: Calculating a Sum
1numbers = [10, 20, 30, 40]
2total = 0
3for num in numbers:
4 total += num
5print(f"The total sum is: {total}")2. The Python while Loop
The while loop repeats a section of code as long as a condition is True. It is an "entry-controlled" loop, meaning the condition is checked before the code runs.
Syntax
1while condition:
2 # Code to repeat
3 # Modification to condition (to avoid infinite loops)Example: Finding a Key
1numbers = [2, 3, 4, 1, 5]
2target = 1
3i = 0
4
5while i < len(numbers):
6 if numbers[i] == target:
7 print(f"Found {target} at index {i}!")
8 break
9 i += 13. Nested Loops
Python allows you to put one loop inside another. This is particularly useful for working with 2D data like matrices or grids.
Example: Traversing a 2D Matrix
1matrix = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5]
6
7for row in matrix:
8 for item in row:
9 print(item, end=' ')
10 print() # New line after each row4. The range() Function
The range() function is a lifesaver when you need to run a loop a specific number of times. It generates an arithmetic progression lazily (saving memory).
| Parameter | Description |
|---|---|
| Start | Beginning of the range (default is 0) |
| Stop | The end point (exclusive) |
| Step | The increment between numbers (default is 1) |
Examples
1# Multiples of 3 under 10
2for i in range(3, 10, 3):
3 print(i) # Output: 3, 6, 9
4
5# Counting backwards
6for i in range(10, 0, -2):
7 print(i) # Output: 10, 8, 6, 4, 25. Loop Control: break, continue, and pass
Sometimes you need to change how a loop behaves on the fly.
Break vs Continue
Break exits the loop entirely. Continue skips the rest of the current iteration and jumps to the next one.
break Example
1for i in range(1, 10):
2 if i == 5:
3 break # Exit loop when i is 5
4 print(i)continue Example
1for i in range(1, 6):
2 if i == 3:
3 continue # Skip printing 3
4 print(i)pass Example
The pass statement is a null operation. It's used as a placeholder for code you haven't written yet.
1for i in range(10):
2 pass # I'll add logic here later!6. The Unique else Clause in Loops
One of Python's most unique features is the else clause for loops. The else block executes only if the loop finishes naturally (i.e., it wasn't stopped by a break).
Logic:
- Loop finished? →
elseruns. - Loop broken? →
elseis skipped.
1# Searching for a number
2numbers = [1, 2, 3, 4, 5]
3target = 10
4
5for n in numbers:
6 if n == target:
7 print("Found it!")
8 break
9else:
10 print("Target was not in the list.")Conclusion
Mastering loops is a fundamental step in becoming a Python pro. Whether you are using for for collections or while for conditions, always remember to keep your logic clean and your terminating conditions sharp.
Happy coding!
Next Step
Combine your knowledge of loops with Conditionals to build powerful, decision-making algorithms.
