Mastering Python Loops: For, While & Nested Loops Explained
What will you learn?
| Concept | Summary |
| For Loop | Repeats a block of code a specific number of times using a sequence. |
| While Loop | Continues running a block of code as long as a condition remains true. |
| Nested Loops | A loop inside another loop, useful for working with grids or tables. |
| Break and Continue | Keywords that alter the flow of loops. break exits, continue skips. |
| Use of Loops in Practice | Loops help automate repetitive tasks, e.g., iterating through lists. |
Introduction: The Power of Loops in Python
When programming, you'll often need to repeat tasks multiple times, like processing every item in a list or generating numbers. Loops make these tasks much easier. Instead of writing repetitive code, loops allow you to automate this repetition with a few lines.
There are two main types of loops in Python: for loops and while loops. Both let you repeat blocks of code, but each is suited for different situations. In this article, you'll learn how to use them, explore nested loops, and master the art of repetition in programming.
The For Loop: Automating Repetition
The for loop allows you to iterate over a sequence (like a list or range) and execute a block of code for each item in that sequence.
Syntax of a for Loop
Here's the basic syntax of a for loop in Python:
for item in sequence:
# code to execute for each item
item: Represents the current item in the sequence.sequence: Could be a list, tuple, string, or a range of numbers.
Example: Python for Loop
Let's look at a simple example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Explanation:
This loop goes through each fruit in the list
fruitsand prints it out. So the output will be:apple banana cherry
Flowchart of a for Loop
Here’s a simple flowchart to show how a for loop works:
Start
↓
Initialize variable
↓
Is there a next item in the sequence?
├── Yes → Execute code → Go to next item
└── No → Exit loop
↓
End
The loop continues until every item in the sequence has been processed.
Common Uses of for Loops
Iterating Over Lists: As shown in the fruit example.
Iterating Over Ranges:
for i in range(5):
print(i)
This will print numbers from 0 to 4.
The While Loop: Repeat Until a Condition is Met
The while loop keeps repeating a block of code as long as a condition is true. It's useful when you don’t know in advance how many times the loop will run.
Syntax of a while Loop
while condition:
# code to run repeatedly
condition: The loop continues running as long as this condition is true.
Example: Python while Loop
x = 1
while x < 5:
print(x)
x += 1
Explanation:
The loop starts with
x = 1and continues untilxis no longer less than 5. Each time,xincreases by 1. Output:1 2 3 4
Flowchart of a while Loop
Here's a flowchart that demonstrates how a while loop works:
Start
↓
Check condition
↓
Is the condition true?
├── Yes → Execute code → Recheck condition
└── No → Exit loop
↓
End
Nested Loops: Looping Inside Loops
You can place one loop inside another loop. These are called nested loops. Nested loops are often used when you need to work with grids, tables, or matrices.
Example: Nested for Loops
for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")
Explanation:
The outer loop runs 3 times, and for each iteration of the outer loop, the inner loop runs 2 times. The output will be:
i: 0, j: 0 i: 0, j: 1 i: 1, j: 0 i: 1, j: 1 i: 2, j: 0 i: 2, j: 1
Example: Nested while Loops
x = 0
while x < 3:
y = 0
while y < 2:
print(f"x: {x}, y: {y}")
y += 1
x += 1
This will produce the same output as the nested for loop example. Nested loops are incredibly useful for multi-level structures like tables, matrices, or combinations of data.
Break and Continue: Controlling Loop Flow
In both for and while loops, you can control how the loop behaves using two important keywords: break and continue.
break Statement
- The
breakstatement exits the loop completely, even if the condition or sequence hasn’t finished.
for i in range(10):
if i == 5:
break
print(i)
Explanation:
- This loop will print numbers from 0 to 4. Once
ireaches 5, thebreakstatement will exit the loop.
continue Statement
- The
continuestatement skips the current iteration and moves to the next one.
for i in range(5):
if i == 3:
continue
print(i)
Explanation:
- The loop will print numbers from 0 to 4, except for 3, which is skipped due to the
continuestatement.
When to Use Each Loop
Use a
forloop when you know the number of iterations in advance (e.g., iterating through a list or a range).Use a
whileloop when you don’t know how many iterations are required, and the condition controls the loop.
Let’s Practice
Practice Problem 1: Write a
forloop that prints the square of each number in a list.numbers = [1, 2, 3, 4, 5] for num in numbers: print(num ** 2)Practice Problem 2: Write a
whileloop that counts down from 10 to 1.x = 10 while x > 0: print(x) x -= 1Challenge: Create a nested loop that prints the multiplication table from 1 to 5.
for i in range(1, 6): for j in range(1, 6): print(f"{i} * {j} = {i * j}")
Test Your Knowledge
What is the difference between a
forloop and awhileloop in Python?When would you use a nested loop? Provide an example.
What happens if you forget to increment a counter in a
whileloop?Explain the purpose of the
breakandcontinuestatements.Write a loop that prints all odd numbers from 1 to 10 using a
forloop.
Key Takeaways from this article
| Concept | Summary |
| For Loop | Use when you know the number of iterations. |
| While Loop | Use when the number of iterations depends on a condition. |
| Nested Loops | Useful for multi-level structures, like grids or tables. |
| Break | Exits the loop early. |
| Continue | Skips the current iteration and moves to the next one. |
Conclusion
Loops are essential for automating repetitive tasks in Python. Mastering the use of for loops, while loops, and nested loops will greatly improve your coding efficiency. Practice writing different types of loops, and soon, you'll be able to tackle complex tasks with ease.
