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

bookWhile 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

ninja.py

copy

Here:

  1. The Ninja moves right until the Ninja sees the sushi next to him;
  2. Moves to the right one more time and picks up the sushi.
question mark

When should you use a while loop?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 4. ChapterΒ 5

Ask AI

expand

Ask AI

ChatGPT

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

SectionΒ 4. ChapterΒ 5
some-alt