Introduction
This is another article where the main focus is just to simulate and demonstrate a certain feature. In this article, is is the feature normally available in programming language. Specifically, it is in Python programming language. Furthermore, the feature is loop or repetition functionality to allow a certain process execution to be carried out for a numerous times. Actually, there is already an article which is also focusing on how to perform loop. But in that article, the loop functionality is using the ‘for’ reserved keyword. It is an article exist in this link with the title of ‘How to use for loop in Python’.
How to use while loop in Python
So, this part will discuss about how to perform loop using while reserved keyword. In case of the while loop, instead of focusing on the number of repetition for executing the process, it focus on the condition or requirement. Specifically, it is focusing to perform loop while the condition or the requirement is met. So, as long as the condition or the requirement is still true, the process will just continue on looping without having to concern about how many times or how many number the process will be carried out. Before going further, the following is the syntax for the while loop in Python programming language :
while conditional_statement : statement;
Using the above syntax pattern for giving an example in order to explain it clearly, below is a pseudo code of a scenario :
while number_is_less_than_10 : print_the_number;
After describing the pseudo code above for designing the scenario, just translate it into a Python programming language’s source code. Below is the translation of the pseudo code above into a Python programming language’s source code :
i = 0; while i < 10 : print(i," is less than 10"); i += 1;
In order to display the output of the above Python programming language. So, below is the execution of the source code in Python command console :
C:\>python Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> i = 0; >>> while i < 10: ... print(i," is less than 10"); ... i += 1; ... 0 is less than 10 1 is less than 10 2 is less than 10 3 is less than 10 4 is less than 10 5 is less than 10 6 is less than 10 7 is less than 10 8 is less than 10 9 is less than 10 >>>
At the above output command execution, there is a specific number times to execute the process. Actually, it is stating the number of times for the process execution in the while conditional statement. But generally, the while conditional statement is focusing on the condition met. Whether it is involving number or not. But normally, it is involving condition where it only has two types of results. Those types of result are true or false for the while conditional statement. If the result is true, it will continue loop and perform the process. On the contrary, it will stop the loop if the result is false.