Welcome! Today we will explore how to design smart programs using nested loops to solve real-world problems.
Before writing code, developers use a software design process. We start by breaking a large problem down into smaller, manageable subproblems.
A nested loop is simply a loop inside another loop. The outer loop acts like an hour hand, while the inner loop spins completely for every single step of the outer loop.
Let us analyze a real-world context: printing a weekly chore chart. The outer loop tracks the days, and the inner loop tracks the chores for each day.
✏️ Worked example
Design a Python program to print a 3x3 grid of star symbols (*) using nested loops.
- Analyze the main problem and break it into two subproblems: printing multiple rows, and printing stars inside each row.
- Write an outer loop to control the rows. We want 3 rows, so we use 'for row in range(3):'.
- Write an inner loop inside the outer loop to control the columns. We want 3 stars per row, so we use 'for col in range(3):'.
- Inside the inner loop, print the star symbol without starting a new line, using 'print("*", end=" ")'.
- After the inner loop finishes, print an empty line using 'print()' to move to the next row.
- Run the code to verify that it outputs three neat rows of three stars each.
Want the full interactive lesson — quiz, animations, and Finn cheering them on?