🌟 Day 7: Nested Loops and Loop Control Statements🌟
Congratulations on making it to Day 7 of the Python for Beginners series! 🎉 Today, we’re going to master nested loop and learn more about loop control statements like break and continue. Let’s make loops your superpower! 💻💪
1. Nested Loops
A nested loop is a loop inside another loop. This is helpful when working with grids, patterns, or multiple levels of iteration.
Example: Printing a 3x3 Grid
For I in range(1, 4): # Outer loop
For j in range(1, 4): # Inner loop
Print(f”({i}, {j})”, end=” “) # Print in one line
Print() # Start a new line after the inner loop finishes
Output:
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
2. Using break in Nested Loops
The break statement can be used to exit the innermost loop it’s in.
For I in range(1, 4): # Outer loop
For j in range(1, 4): # Inner loop
If j == 2:
Break # Exits the inner loop when j == 2
Print(f”({i}, {j})”, end=” “)
Print()
Output:
(1, 1)
(2, 1)
(3, 1)
3. Using continue in Nested Loops
The continue statement skips the current iteration of the loop but doesn’t stop the entire loop.
For I in range(1, 4): # Outer loop
For j in range(1, 4): # Inner loop
If j == 2:
Continue # Skips when j == 2
Print(f”({i}, {j})”, end=” “)
Print()
Output:
(1, 1) (1, 3)
(2, 1) (2, 3)
(3, 1) (3, 3)
4. Triangle Pattern Example
Here’s a creative way to use nested loops to print a pattern.
Rows = 5
For I in range(1, rows + 1): # Outer loop for rows
For j in range(1, I + 1): # Inner loop for columns
Print(“*”, end=” “)
Print() # Move to the next row
Output:
*
* *
* * *
* * * *
* * * * *
Practice Challenge
1. Create a program to print a multiplication table (from 1x1 to 10x10) using nested loops.
2. Write a program to display all combinations of two dice rolls (e.g., (1,1), (1,2)).
3. Build a pattern with numbers, like:
1
1 2
1 2 3
1 2 3 4
Starting tomorrow, we’ll dive into data structures in Python, beginning with lists and their powerful operations! Get ready for another exciting week. 🚀✨