Monday, August 25, 2025

๐ŸREAL LIFE EXAMPLE

Nested Loops in Python

Loops inside loops? Yes! That’s what we call nested loops. They’re super useful when working with multi-dimensional data or patterns.

What are Nested Loops?

A nested loop means placing one loop inside another. The inner loop will run completely for every single iteration of the outer loop.

Syntax of Nested Loops


for outer in sequence1:
    for inner in sequence2:
        # statements

while condition1:
    while condition2:
        # statements

Example 1: Multiplication Table


for i in range(1, 4):        # Outer loop
    for j in range(1, 4):    # Inner loop
        print(i, "*", j, "=", i*j)
    print("---")

Output:


1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
---
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
---
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
---

Example 2: Nested While Loop


i = 1
while i <= 3:
    j = 1
    while j <= 3:
        print(f"i={i}, j={j}")
        j += 1
    i += 1

๐Ÿ’ก Real-Life Use Cases

  • Working with 2D arrays (matrices, tables, spreadsheets).
  • Printing patterns (like stars or shapes).
  • Nested data structures (lists inside lists, JSON).
  • Combinatorics (generating pairs or combinations).

Example: Star Pattern


rows = 5
for i in range(1, rows+1):
    for j in range(i):
        print("*", end="")
    print()

Output:


*
**
***
****
*****

⚠️ Common Mistakes

  • Indentation Errors: Misplacing indentation makes the inner loop part of the outer unintentionally.
  • Infinite Loops: Forgetting to update variables in nested while loops.
  • Too Many Loops: Nested loops can get very slow for large data. Always check if there’s a better solution.

๐Ÿ’ก Practice Challenges

  1. Use nested loops to print a 10x10 multiplication table.
  2. Print a right-angled triangle of numbers.
  3. Traverse a 2D list (matrix) using nested loops and print all elements.
  4. Write a nested loop to find all pairs of numbers (i, j) where i and j range from 1 to 5.

What’s Next?

Now that you understand nested loops, the next step is learning about functions in Python, so you can organize your code into reusable blocks.

➡️ Next: Functions in Python

⬅️ Back to Main Page

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??