While Loops in Python
While Loops in Python
In a while loop, we define the condition, not the number of iterations. The loop stops when the condition is
. This is the general syntax of a while loop:
For example:
Break and Continue We can also use
and
with while loops and they both work exactly the same:
stops the while loop immediately.
stops the current iteration and starts the next one. For example:
The
Clause We can also add an
clause to a while loop. If
is found, the
clause doesn’t run but if the
statement is not found, the
clause runs. In the example below, the
statement is not found because none of the numbers are even before the condition becomes
, so the
clause runs.
This is the output:
But in this version of the example, the
statement is found and the
clause doesn’t run:
The output is:
Infinite While Loops When we write and work with while loops, we can have something called an “infinite loop.” If the condition is never
, the loop will never stop without external intervention. This usually happens when the variables in the condition are not updated properly during the execution of the loop. For example:
S.Schins BASICS
Python Basics Examples