While Loops
Swipe to show menu
So far, you have used loops when you knew exactly how many times an action should repeat. But in the Ninja game, that is not always the case. Sometimes you do not know how many times you need to execute commands.
A while loop repeats code as long as a condition is True. Instead of saying, "Do this 5 times", you say, "Keep doing this while a condition remains True".
Here's the basic structure:
while condition:
# Actions to repeat
The code inside the loop keeps running
until the condition becomes False.
Imagine the Ninja is walking along a path and does not know where the sushi is.
ninja.py
Here:
- The Ninja moves right until the Ninja sees the sushi next to him;
- Moves to the right one more time and picks up the sushi.
Everything was clear?
Thanks for your feedback!
SectionΒ 4. ChapterΒ 5
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
SectionΒ 4. ChapterΒ 5