Nested For Loop
Introduction:
- In Python, a
forloop can be nested inside anotherforloop. This is known as nesting, and it allows you to iterate over multiple sequences at once.
Examples:
- Print Triangular Pattern:
- This example demonstrates how to use nested
forloops to print a triangular pattern. Python Program:
pythonn = 6 for x in range(n): for y in range(x + 1): print('* ', end=' ') print()Output:
* * * * * * * * * * * * * * * * * * * * *
- This example demonstrates how to use nested
- Iterate Over List of Lists:
- This example shows how to use nested
forloops to iterate over a list of lists and print each element. Python Program:
pythoninput = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ] for inner in input: for element in inner: print(element)Output:
a b c d e f
- This example shows how to use nested
Exercises:
- Create a Multiplication Table:
Write a program to create a multiplication table from 1 to 5 using nested
forloops.pythonfor i in range(1, 6): for j in range(1, 6): print(i * j, end=' ') print()
- Print a Pyramid Pattern:
Write a program to print a pyramid pattern of stars using nested
forloops.pythonrows = 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
forloops in Python. Nested loops are useful for iterating over multiple sequences and creating complex patterns. Practice these examples to get comfortable with using nestedforloops in your Python programs!