Can loops be nested?

QuestionsQuestions8 SkillsProPython Control StructuresNov, 19 2025
0125

Yes, loops can be nested in Python. This means you can place one loop inside another loop. Here's an example using nested for loops:

for i in range(3):  # Outer loop
    for j in range(2):  # Inner loop
        print(f"i: {i}, j: {j}")

In this example, the outer loop iterates over the range of 3, and for each iteration of the outer loop, the inner loop iterates over the range of 2. The output will be:

i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1

Each iteration of the outer loop completes all iterations of the inner loop before moving to the next iteration of the outer loop. Nested loops are commonly used for tasks that involve multi-dimensional data structures, such as matrices.

0 Comments

no data
Be the first to share your comment!