Nested For Loop

Introduction:

  • In Python, a for loop can be nested inside another for loop. This is known as nesting, and it allows you to iterate over multiple sequences at once.

Examples:

  1. Print Triangular Pattern:
    • This example demonstrates how to use nested for loops to print a triangular pattern.
    • Python Program:

      python
      n = 6
      
      for x in range(n):
          for y in range(x + 1):
              print('* ', end=' ')
          print()
      
    • Output:

      *  
      *  *  
      *  *  *  
      *  *  *  *  
      *  *  *  *  *  
      *  *  *  *  *  *  
      
  2. Iterate Over List of Lists:
    • This example shows how to use nested for loops to iterate over a list of lists and print each element.
    • Python Program:

      python
      input = [
          ['a', 'b', 'c'],
          ['d', 'e', 'f'],
      ]
      
      for inner in input:
          for element in inner:
              print(element)
      
    • Output:

      a
      b
      c
      d
      e
      f
      

Exercises:

  1. Create a Multiplication Table:
    • Write a program to create a multiplication table from 1 to 5 using nested for loops.

      python
      for i in range(1, 6):
          for j in range(1, 6):
             print(i * j, end='  ')
          print()
      
  2. Print a Pyramid Pattern:
    • Write a program to print a pyramid pattern of stars using nested for loops.

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

Summary:

  • In this tutorial, we learned how to write nested for loops in Python. Nested loops are useful for iterating over multiple sequences and creating complex patterns. Practice these examples to get comfortable with using nested for loops in your Python programs!