Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Introduction to Loops | Loops
Python Ninja

bookIntroduction 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

ninja.py

copy

With a for loop, you can write:

ninja.py

ninja.py

copy

We will look at the syntax for i in range(value) in more detail later.

Note
Note

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()
question mark

What does this code do?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 4. ChapterΒ 1

Ask AI

expand

Ask AI

ChatGPT

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

SectionΒ 4. ChapterΒ 1
some-alt