Python Lessons – 2.6 WHILE Loop

Python Lesson - 2.6 the WHILE loop

The WHILE construct

In the IF ELSE construct we saw that a condition was evaluated and if this was checked (True) a series of operations were performed otherwise (False) others were executed.

Now the WHILE construct likewise provides IF with the evaluation of a condition and if this is verified (True) a series of operations are performed, but at the end of these, instead of giving back control to the flow of the program and exit the construct, the initial condition is evaluated again. If this will still be checked (True) then the operations carried out in the previous cycle will be repeated again (False).

So a WHILE construct is nothing more than a loop (loop) in which operations are repeated until (WHILE) the condition that controls it is satisfied. This type of operation is called iteration.

Note: it is normal that for a good programming the instructions within the WHILE loop must in some way affect the value or values ​​evaluated in the condition, otherwise there would be an infinite cycle.

The result of the previous cycle is

The break clause

We have seen that the instructions within a WHILE loop are repeated continuously until the initial condition is met. But sometimes we need to stop the cycle unconditionally and continue with the following instructions. This is possible by inserting the break statement within the WHILE construct.
Generally, the break statement is always inserted within a WHILE loop through an IF that evaluates an additional condition necessary to know if it is necessary to exit unconditionally from the cycle.

The result of this program is

As you can see from the code you used  True directly in the condition, this to create an infinite loop.

The continue clause

There is an additional instruction that can be used within loops or loops and is called continue. This command, if executed, continues the cycle starting from the first instruction and skipping the execution of the following instructions.

If you run it, you get:

As you can see, the continue statement causes the string to skip when the value of the variable equals 3.

⇐ Go to Python Lesson 2.5 – The precedence of the operators

Go to Python Lesson 2.7 – Lists ⇒

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.