In this lesson we will do some examples on the use of the while loop in Python, in order to consolidate what was explained in the last lesson.
while loop Python – Countdown with the while loop
Implement an algorithm that performs a countdown, i.e. displays, for example, the numbers from 10 to 1 in descending order.
Clearly in this case there is no input value to enter, we start from a variable that we call n and that we initialize at 10 and then we decrease it by one each time.
So here is the code in Python:
n = 10
while n > 0:
print(n)
n -= 1
Infinite while loop in Python
Let’s start with the example just proposed to introduce the concept of an infinite loop.
Then let’s assume that we make a mistake in the indentation and therefore write:
n = 10
while n>0:
print(n)
n -= 1
In this case n -= 1 is never executed because the condition n > 0 is always true as the variable n does not change.
In fact, if you run the script, the shell will always show 10, because it will never exit the loop. The print(n) instruction is in fact executed until n > 0 and this condition is always true.
while loop never executed in Python
Let’s now take an example of a cycle that will never run. For example, suppose we get the wrong condition and write n <0.
The starting value is 10 and is not less than 0, so in this case the cycle will never be executed.
So here’s the code below:
n = 10
while n < 0:
print(n)
n-=1
Let's try the produced codes as an example in the online Python compiler below:
This was just a trivial example of using the while loop in Python, feel free to comment in the comments below.
Some useful links
How to find the maximum of N numbers