ninja.py
Back 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.
12for i in range(3): print(i)
ninja.py
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,
jis used for the inner loop andifor the outer loop.
This code controls the Ninja so it collects sushi in rows of increasing length.
- The
forloop runs 5 times; - The variable
ichanges on each iteration: 0, 1, 2, 3, 4.
Note
In Python, counting starts from 0.
On each iteration:
iis passed intocollect_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.
Swipe to start coding
Solution
Explore other courses in Catalog
Thanks for your feedback!
ninja.py
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat