Introduction to Loops
Swipe to show menu
As you continue playing the Ninja game, you will notice something important: the Ninja often needs to do the same action many times.
For example:
- Move forward several tiles;
- Collect multiple pieces of sushi;
- Repeat the same path across the map.
Writing the same command again and again works, but it quickly becomes long and hard to read. This is where loops come in. A loop lets you tell Python to repeat an action multiple times.
Instead of writing the same line over and over, you write it once, and Python repeats it for you.
What Is a for Loop?
A for loop is a way to repeat a block of code a specific number of times.
Now see how this idea applies to the Ninja game. Imagine the Ninja needs to pick 4 sushi in a row. Without a loop, you would write:
ninja.py
With a for loop, you can write:
ninja.py
We will look at the syntax for i in range(value) in more detail later.
All code inside a for loop must be indented under the loop line. For example, the code below does not work because it is not indented correctly:
for i in range(4):
ninja.go_up()
ninja.pick_sushi()
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat