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.
a = 0
while a <= 4:
print("sono nel ciclo WHILE")
a += 1
print("Fine ciclo")
The result of the previous cycle is
>>>
sono nel ciclo WHILE
sono nel ciclo WHILE
sono nel ciclo WHILE
sono nel ciclo WHILE
sono nel ciclo WHILE
Fine ciclo
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.
i = 0
while True:
print(i)
i += 1
if i > 4:
break
print("Sono fuori dal ciclo")
The result of this program is
>>>
0
1
2
3
4
Sono fuori dal ciclo
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.
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
print("Sono fuori dal ciclo")
If you run it, you get:
>>>
0
1
2
4
5
Sono fuori dal ciclo
As you can see, the continue statement causes the string to skip when the value of the variable equals 3.