...

/

Looping with Edward

Looping with Edward

Learn about loops and their applications.

So far, our friend Edward has been moving one step at a time using the move() function. But in his vast spaceship, Edward has to walk long distances. Often, Edward does not know how many steps he has to take. The only point where Edward should stop is if the path ahead is blocked.

Press + to interact
Sample stage 1
1 / 3
Sample stage 1

There will be multiple paths of varying lengths, and we won't always be there to tell Edward how many steps to take. Can we somehow teach Edward to keep on moving until he finds that the path ahead is blocked?

It turns out that the while keyword in Python allows us to continuously perform an action until a condition is met. Remember using conditions for code execution before? While exploring the conditionals (if-else), we saw how the execution depended on boolean conditions. Similarly, the conditions for loops are also represented by boolean values. Our friend Edward has a check functionality that lets it know if he has achieved his goal or not (a boolean condition). This functionality can be accessed by calling the function goal_not_achieved(). It will return True if we need to keep moving and False if we are done with the task.

The snippet below is a template for implementing while in the code. It can be read as follows: while the specified condition is true, keep executing the instruction in the loop.

while condition:
instruction
Template for a while loop
...