Nested Loops
Nested loops are loops inside loops. They allow us to perform operations on multi-dimensional data structures or execute repeated actions within an iterative process. Practice these problems to strengthen your understanding of nested loops.
Practice Problems
Problems Index
- Print a square pattern of
*
withn
rows and columns. - Print a right-angled triangle pattern of
*
. - Generate a multiplication table up to
n
. - Create a pyramid pattern of numbers.
- Print the following pattern for
n
:1 12 123 1234
- Input a list of lists and calculate the sum of all elements.
- Print all pairs of elements from two lists.
- Find the transpose of a 2D matrix.
- Print a pattern where each row contains numbers from 1 to the row number.
- Generate a checkerboard pattern with alternating
0
and1
.
Try It Yourself
Now that you’ve reviewed the problems, practice them below using the code runner!
Pyground
Play with Python!
Output:
Solutions
Solutions
-
Print a square pattern of
*
withn
rows and columns.Show Code
n = int(input("Enter the size of the square: ")) for i in range(n): for j in range(n): print("*", end=" ") print()
-
Print a right-angled triangle pattern of
*
.Show Code
n = int(input("Enter the height of the triangle: ")) for i in range(1, n + 1): print("*" * i)
-
Generate a multiplication table up to
n
.Show Code
n = int(input("Enter the table size: ")) for i in range(1, n + 1): for j in range(1, n + 1): print(f"{i * j:4}", end=" ") print()
-
Create a pyramid pattern of numbers.
Show Code
n = int(input("Enter the height of the pyramid: ")) for i in range(1, n + 1): print(" " * (n - i) + " ".join(str(x) for x in range(1, i + 1)))
-
Print the following pattern for
n
:1 12 123 1234
Show Code
n = int(input("Enter the number of rows: ")) for i in range(1, n + 1): for j in range(1, i + 1): print(j, end="") print()
-
Input a list of lists and calculate the sum of all elements.
Show Code
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] total = 0 for row in matrix: for num in row: total += num print("Total sum:", total)
-
Print all pairs of elements from two lists.
Show Code
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] for item1 in list1: for item2 in list2: print(f"({item1}, {item2})")
-
Find the transpose of a 2D matrix.
Show Code
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] transpose = [] for i in range(len(matrix[0])): row = [] for j in range(len(matrix)): row.append(matrix[j][i]) transpose.append(row) print("Transpose of the matrix:", transpose)
-
Print a pattern where each row contains numbers from 1 to the row number.
Show Code
n = int(input("Enter the number of rows: ")) for i in range(1, n + 1): for j in range(1, i + 1): print(j, end=" ") print()
-
Generate a checkerboard pattern with alternating
0
and1
.Show Code
n = int(input("Enter the size of the checkerboard: ")) for i in range(n): for j in range(n): print((i + j) % 2, end=" ") print()