Looping with Edward
Learn about loops and their applications.
We'll cover the following...
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.
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
Our task is to teach Edward to follow a simple statement: while the goal is not achieved, he should move. In the following code, we have translated this statement into working code to help Edward reach the end goal.
Lesson learned: Instead of writing the same instruction multiple times, we can convert it into a small block of code that repeats itself while the condition is true.
Congratulations! We have successfully implemented a loop to move Edward.
Programming with loops
Just like we programmed Edward to move repeatedly using the loop, wouldn’t it be great for programmers if they could make the computer execute a block of code repeatedly while a condition is True?
For instance, if you are required to print 1 three times, what would be your code?
Let’s imagine we need to do so ten times instead of three. Of course, we’d have to write ten lines of code. We’ll drag our feet a little, but we would still have to write those ten lines of code. But now, suppose that we get into a situation where we have to print 1 a thousand times! Would we protest? Or sob a little and start writing long and tedious code where every line does the same thing over and over again?
Additionally, to keep track of the number of times we have called the print function, we need to use a variable. We initialize a variable named counter with 0, and increment its value by 1 each time we print.
counter = 0print(1)counter = 1print(1)counter = 2print(1)counter = 3print(1)counter = 4print(1)counter = 5print(1)counter = 6print(1)counter = 7print(1)counter = 8print(1)counter = 9print(1)counter = 10
A task of this nature is repetitive and tedious. Thankfully, we can use the while loop to stay safe this time. Let’s see what we should use this time as the condition for looping.
We know there are comparison operators, such as < or > that we can use to check whether a number is smaller or greater than a certain value. We could use these operators to our advantage and keep on printing while the number of 1s we have printed is less than 1000! This will also make our code neat and pleasing to look at. Moreover, these three lines of code are much more efficient than us having to manually print those values ourselves. Let’s start trying with just ten lines initially.
Oh no! This keeps printing until the Python program has had enough!
Why don’t we seek the help of Educative’s AI mentor?
Looks like we forgot to update the counter, in the absence of which the value of the counter remains <= 10 forever. This was
Press the "Run" button to check if we've programmed the loop correctly this time:
Oh no! That didn’t work either! Should we give up? Of course not! We just need to think and think more instead of giving up. We always think of why things don’t work the way we expect them to. We do this persistently, like being in a loop, till we succeed. With that motivation in mind, here’s another attempt at solving the problem:
But what is the difference between the two pieces of code here?
We tried Code A, and it kept printing 1 forever. Why does Code B work when we’ve only made a tiny change of indentation in the last line. Run Code B first, but then think about why it 1.
Printing the counter
To observe the difference in functionality of the two codes, let’s print(counter) instead of print(1). Remember, our algorithmic idea was to initialize a counter to 0, and right after printing the number, increase the counter by 1 so that the while loop only works ten times.
Code A
counter = 0
while counter <= 10:
print(counter)
counter = counter + 1
Code B
counter = 0
while counter <= 10:
print(counter)
counter = counter + 1
Try running both code snippets one by one in the widget below and observe the output.
In Code A, the value never updated! It was always zero, so the condition to stop the loop was never met. The code behaves this way because the counter-updating code statement is indented at the same level as our loop declaration and is not detected as a part of the loop by Python. On the other hand, the counter-updating statement has the correct indentation in Code B. This way, this statement is considered a part of the loop, and we can see the counter updating on each iteration until it exceeded 10 and the loop stopped executing.
Challenge
Can you prove that you can write a program that prints a thousand numbers on the screen? And that you can do that in just a few seconds?
Recap
Key takeaways:
Purpose of loops: Loops allow us to repeatedly execute a portion of our code.
Loop stoppage criteria: Loops end when a boolean condition turns
False.Importance of indentation: The code to be executed in a Python loop is to be properly indented.