Q.Program 6-6: Program to print the characters in the string ‘PYTHON’ using for loop.
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Concept understanding — Nested For Loops
Nested For Loops: Loops Inside Loops
Imagine you're a teacher taking attendance in a school with 3 classrooms, each having 5 students. You go to Room 1, call out all 5 names, then move to Room 2, call out all 5 names, then Room 3, call out all 5 names. That's a loop inside a loop — for each classroom, you run through all students.
That's the entire intuition. A nested for loop is simply a for loop placed inside the body of another for loop. The outer loop runs once, and for that single iteration, the inner loop runs completely from start to finish. Then the outer loop moves to its next iteration, and the inner loop runs completely again.
The Precise Statement
for i in range(3): # outer loop
for j in range(5): # inner loop
print(i, j)
Here's exactly what happens, step by step:
ibecomes 0. Enter the inner loop.jruns through 0, 1, 2, 3, 4 — printing each pair(0,0),(0,1), ...,(0,4).- Inner loop finishes.
ibecomes 1. Enter the inner loop again. jruns through 0, 1, 2, 3, 4 again — printing(1,0),(1,1), ...,(1,4).- Inner loop finishes.
ibecomes 2. Inner loop runs a third time. jruns through 0, 1, 2, 3, 4 — printing(2,0), ...,(2,4).
Total printed lines: .
The inner loop completes all its iterations for each single iteration of the outer loop. The total number of times the inner body executes is:
Why This Matters
Nested loops are how you work with tables, grids, matrices, and any data that has rows and columns. A 2D list (like a spreadsheet) is naturally processed with one loop for rows and another for columns.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix: # outer: pick a row
for element in row: # inner: pick each element in that row
print(element, end=' ')
print() # new line after each row
Output:
1 2 3
4 5 6
7 8 9
The outer loop selects a row; the inner loop walks across that row's elements. When the inner loop finishes, the outer loop moves to the next row.
Common Mistake …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.