Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Back and Forth Loops | Loops
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Python Ninja
SectionΒ 4. ChapterΒ 10
ninja.py

ninja.py

bookBack and Forth Loops

Swipe to show menu

You have already used for loops a few times in this course. At some point, you may have wondered what the i and range(7) in this line actually mean:

for i in range(7):

What does range(7) Do?

range(7) creates a sequence of numbers:

0, 1, 2, 3, 4, 5, 6

What is i?

i is a variable that takes one value from range(7) on each loop iteration.

You can think of i as a counter that Python updates automatically.

12
for i in range(3): print(i)
copy
ninja.py

ninja.py

copy

Note

In Python, it is not recommended to use the same variable name in both the outer and inner loops. This can make the code confusing and harder to understand.

That is why in the example, j is used for the inner loop and i for the outer loop.

This code controls the Ninja so it collects sushi in rows of increasing length.

  • The for loop runs 5 times;
  • The variable i changes on each iteration: 0, 1, 2, 3, 4.

Note

In Python, counting starts from 0.

On each iteration:

  • i is passed into collect_sushi;
  • The Ninja moves down to the next row.

Here, i represents how many sushi pieces should be collected on that row.

How collect_sushi Works

The loop runs n times. On each repetition it picks up sushi and moves the Ninja one step to the right. So:

  • When n = 0, nothing happens;
  • When n = 1, the Ninja picks up 1 sushi;
  • When n = 4, the Ninja picks up 4 sushi.
Task

Swipe to start coding

Solution

Explore other courses in Catalog

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 4. ChapterΒ 10
ninja.py

ninja.py

Ask AI

expand

Ask AI

ChatGPT

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

some-alt