A “loop” is how we call a process that repeats itself as long as some condition is true. As soon as this condition becomes false, the process continues as the loop is being left behind.

     We state this condition by the usage of the word “while” followed by the condition that needs to be true in order to initialize the loop.

     For example:

     As you can see, the condition is followed by “:”. This is the only way for the computer to know which is the condition that needs to be true in order to continue with the loop.  The condition will always be the one between the word “while” and “:”.

      The evaluation “!=” means “ is not ” and “==” means “is”.
      The previous conditions which is “x != 0” means “x is not 0”. But if we had “x==0” it would mean “x is 0”.
      We can also use “<(smaller than), “>(greater than), “<=(lower or equal to)and “>=(greater or equal to).


     The actions being done inside the loop will be held in the following lines. These need to be intended to be considered as part of the loop.

      What this program does is that is asks the user for a number, this number is stored in two diferent variables which are “x” and “x2”. The first one will remain the same and the second one will be altered during the loop.

      If the value given by the user is not 0, then the program will enter the loop.
In this loop, “x2” will be altered until it becomes “0”. The number of times this variable is being changed will be determined by the variable “count”.

     The next line is not intended, which means is not part of the loop. Therefore, this action will take place once “x2” is 0 (which is the condition that breaks the loop).
      
       In the end, what this program does is to determine how far from 0 is the number the user gave. After that, it prints the equation that need to be done to this number in order to turn it into 0.

       Another example more complicated than the one stated before ca be this one:

      In this program, the computer chooses a random number between 0 and 100 and it asks the user to guess it. The user has an unlimited number of tries to guess the number.

      The loop initializes when the number given by the user is not the same as chosen by the computer and it finishes once the user guesses the number. During the loop, there is a variable called “count” that will count how many times the loop is repeated; which is the same number of tries the user had.

CC BY 4.0 Loops with While by Frida Diaz is licensed under a Creative Commons Attribution 4.0 International License.