A nested loop is a loop that is contained inside another loop.
This means that one loop will execute its entire iteration for each iteration of the enclosing loop.
Nested loops are commonly used to iterate over two-dimensional data structures like lists of lists or matrices.
They can also be used for other scenarios where multiple iterations are required.
Here’s an example of a nested loop that prints a multiplication table from 1 to 10:
# Nested loop example - Multiplication table from 1 to 10 for i in range(1, 11): # Outer loop: i iterates from 1 to 10 for j in range(1, 11): # Inner loop: j iterates from 1 to 10 result = i * j print(f"{i} x {j} = {result}") print("") # Add a blank line after each table to separate them
In this example, we have two loops: an outer loop and an inner loop. The outer loop iterates from 1 to 10, and for each iteration, the inner loop iterates from 1 to 10 as well. The result
variable holds the multiplication of i
and j
, and the formatted string is printed to display the multiplication table for each value of i
from 1 to 10.
The output of the above code will be:
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 ... (omitted for brevity) 10 x 8 = 80 10 x 9 = 90 10 x 10 = 100
As you can see, for each value of i
, the inner loop iterates from 1 to 10, and the corresponding multiplication table is printed. This is an example of a nested loop in Python.
Here’s another example of a nested loop that prints a pattern of stars:
# Nested loop example - Printing a star pattern rows = 5 # Number of rows in the pattern # Outer loop to iterate over each row for i in range(rows): # Inner loop to print the stars in each row for j in range(i + 1): print("*", end="") print("") # Move to the next line after printing each row
In this example, we have an outer loop that iterates from 0 to 4 (since range(rows)
generates numbers from 0 to rows-1
). For each value of i
, the inner loop iterates from 0 to i
. The inner loop is responsible for printing the stars in each row. The number of stars printed in each row depends on the value of i
.
The output of the above code will be:
* ** *** **** *****
As you can see, the number of stars increases from 1 to 5 as we go from the first row to the last row.
This pattern is created using nested loops, with the outer loop controlling the number of rows, and the inner loop controlling the number of stars printed in each row.
Read More;
- How to write update query in MySQL in Python?
- Simple Example Python Programs for Practice [Beginners ]
- What is for loop in python with example [10 Examples]
- Multiprocessing Python Example For Loop
- What is a list () in Python With Example
- What is a dictionary in Python example?
- What are the types of variables in Python?
- Can you run a for loop on a dictionary Python?
- Vimrc Example for Python (Vim configuration)
- What is elif Statement in Python With Example
- How Do You Write Q-learning in Python?
- How do you automate daily tasks in Python?