Nested 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:
- The same movement-and-collection pattern;
- Shift position;
- 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
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.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat