Studyfin Studyfin ✨ Sign up free

Intro to Python

Grade 7 · Coding · Free lesson

Hi there! I am Studyfin, your coding tutor. Today, we will learn how to plan and build neat Python programs using loops inside loops!

When coders create software, they do not just start typing. They use a software design process. First, they break a big real-world problem down into smaller subproblems.

letters

A loop is code that repeats. A nested loop is simply a loop placed inside another loop. Think of a clock: the inner minute hand loops sixty times for every single outer hour loop.

Nested Loop Concept

Let us solve a real-world problem: printing a grid of stars for a video game level. We can split this into two subproblems. Subproblem A is drawing a single row of stars. Subproblem B is repeating that row down the screen.

Row 1: Active Row 2: Active Row 3: Active
✏️ Worked example

We want to write a Python program that prints a grid of stars with 3 rows and 4 stars in each row. Let us design and build this step-by-step.

  1. Identify the subproblems. Subproblem 1: Write a loop that prints 4 stars side-by-side in one row.
  2. Write the inner loop code for Subproblem 1. In Python, this is: for star in range(4): print('*', end=' ').
  3. Identify Subproblem 2: We need to repeat this entire row 3 times down the screen.
  4. Wrap the inner loop inside an outer loop that runs 3 times: for row in range(3):
  5. Combine them. Inside the outer loop, place the inner loop, and add a blank print() at the end of each row to move to the next line.
  6. Run the final code! The outer loop runs once, triggers the inner loop to print 4 stars, moves to a new line, and repeats 2 more times.
snake
Want the full interactive lesson — quiz, animations, and Finn cheering them on?

More Coding lessons