CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Python – Control Flows – The while Statement

We have discussed if Statement in our previous Article “Python – Control Flows – The if Statement“. The if Statement is one of the control statements in Python, used to control the flow of the Program depending on the conditional expression. The code is written inside the if Statement is going to execute only once depending on the conditional expression. How to repeatedly execute the statements? Where while Statement comes into the picture.

The while Statement in Python

This is a Compound Statement and the statements written in while Statement is going to execute as long as the conditional expression evaluates to true. It is important to note that one of the statements written in while should be helpful to make the conditional expression false. Otherwise, the loop will execute infinitely.

In the below example, the “a = a – 1” statement is helpful to make the conditional expression false after a couple of iterations. This statement is important; otherwise, the loop will execute infinitely.

>>> a = 3
>>> while a > 0:
...    print(a)
...    a = a - 1
... 
3
2
1

else within while in Python

while Statement has two blocks. The code written in while block is going to execute repeatedly as long as the conditional expression is true. When the expression is false, the statements written in else block will execute. The else Statement within while Statement is optional.

Below is the code example, which displays each element in a list. Once all elements are displayed, the statements in else block will execute.

>>> l = ["Australia", "Belgium", "Canada"]
>>> i = 0
>>> while i < 3:
...    print(l[i])
...    i = i + 1
... else:
...    print("-- end of list --")
... 
Australia
Belgium
Canada
-- end of list --
>>>

This is IMPORTANT to note that the statements written in else block will execute ONLY once when the conditional expression evaluates to false.

We discuss more topics as we go.

/Shijit/

Python – Control Flows – The while Statement

2 thoughts on “Python – Control Flows – The while Statement

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top
Exit mobile version