Sure! Here are five examples of programs in Python that use nested for loops:
-
Print a pattern of stars:
python for i in range(5): for j in range(i+1): print("*", end="") print()Output:* ** *** **** ***** -
Generate multiplication table:
python for i in range(1, 11): for j in range(1, 11): print(i*j, end="\t") print()Output:1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 - Print a pyramid pattern:
python rows = 5 for i in range(rows): for j in range(rows-i-1): print(end=" ") for j in range(i+1): print("*", end=" ") print()Output: ``` *- * * * * * * * * * * * * * ```
-
Generate a list of all possible combinations of two lists:
python list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] combinations = [] for i in list1: for j in list2: combinations.append((i, j)) print(combinations)Output:[(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')] - Calculate the sum of elements in a 2D list:
python matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] total_sum = 0 for row in matrix: for element in row: total_sum += element print(total_sum)Output:45
These are just a few examples of programs that use nested for loops in Python. You can modify them or create your own programs based on your requirements.
Loading...