Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Nested For Loops | Loops
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Python Ninja

bookNested For Loops

Swipe to show menu

So far, you have used loops to repeat small action patterns β€” not just single commands, but short sequences of movements and actions.

But sometimes, that pattern needs to be repeated again. This is where nested loops become useful.

A nested loop is simply a loop inside another loop:

  • The inner loop describes a repeating pattern;
  • The outer loop controls how many times that whole pattern runs.

You can think of it like this: "Repeat this sequence… and do that multiple times".

Repeating Patterns on a Grid

Imagine a map where the Ninja must perform:

  1. The same movement-and-collection pattern;
  2. Shift position;
  3. Repeat that same pattern again.

Writing this without nested loops would mean copying a lot of code. Nested loops let you describe this structure clearly and compactly.

ninja.py

ninja.py

copy

Outer loop

for i in range(4):

This loop controls how many times the overall pattern repeats. Each iteration represents one full pass of the same strategy.

Inner loop

for j in range(3):
    ninja.go_right()
    ninja.pick_sushi()

This loop defines the repeated action pattern: move and collect sushi.

Moving to the next area

ninja.go_left()
ninja.go_left()
ninja.go_down()

After completing the inner loop, the Ninja shifts position and prepares to repeat it again.

question mark

Look at the code below. How many times does the Ninja pick up sushi in total?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 4. ChapterΒ 8

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

SectionΒ 4. ChapterΒ 8
some-alt