A while loop
is a control structure used to repeat the execution of a statement or group of statements as long a condition evaluates to True
.
The following is the basic syntax of while loops:
while <condition>:
<statements>
The while
keyword signals the beginning of the definition of a while loop.
The condition
is an expression that is evaluated to determine whether the loop should continue to execute or not. If the expression evaluates to True
, the statements under the loop block are executed and then the condition is tested again, this cycle continues until when the condition will fail, only then will the program execution move to the statements below the loop.
The condition expression usually involves some kind of comparison, such as checking if a variable is equal to a certain value, if a number is greater/less than another number, etc.
Unlike in for loops, the exact number of iteration is not known in advance in while loops. Instead, the loop body is responsible of altering the condition variables as necessary, so that the condition eventually fails making the loop to terminate.
The various parts of the while loop are as shown below:
In the above example, the statements inside the loop's body will be executed as long as the value of i
is less than 10. Inside the loop's body, the value of i
is displayed, and then its value is incremented by 1. This means that eventually, the value of i
will be greater than or equal to 10 in which case the condition(i < 10
) will fail causing the loop to terminate.
The flow chart of the above loop is as shown in the following image.
Let us look at another example.
The above loop is like a reversed version of the previous one. We are starting with the value of i
being 9, then during each iteration we are decrementing it with one. When i
becomes less than or equal to 0, the condition fails and, therefore, the loop terminates.
Infinite while loops
An infinite while loop is one that the condition never fails/evaluates to False
. This leads to the loop running without ever stopping.
While infinite while loops have some useful applications, they can in some cases cause a program to crash or become unresponsive, as it continuously uses up system resources. This is usually the case when the infinite loop happens unintentionally, due to an error in the loops logic.
The most obvious example of an infinite loop is as shown below.
while True:
#do something
The statements defined inside the body of the above loop will be executed infinitely, until you forcefully stop it or the program crashes.
The following is a not so-obvious example of a while loop.
i = 1
while i != 10:
print(i)
i += 2
The above example is an infinite loop because when you start with integer i
with a value of 1 and keep on cumulatively adding 2 , the value of i
will go on like 1, 3, 5, 7, 9, 11, ..., and thus it will never be10 , this means that the condition(i != 10
) will never fail and so the loop runs infinitely.
While loop with sequences and collections
We can use the while loop to iterate over sequences by using an index variable to keep track of the current position within the sequence. For example to iterate a list we start by setting the initial index value as 0 then increment it after every iteration to get the next index.
In the case with non-sequence collections such as sets and dictionaries, we can use the while loops with the collection's retrieval methods to get values.
The above loop will continue to execute until the set is empty. On each iteration, the pop() method is used to remove an element from the set and print it.
Multiple conditions
Multiple conditions can be combined with logical operators such as and
, or
, and not
, they help us to create complex loops that can accomplish more advanced tasks
loop Control Statements
Various statements can be used with while loops to alter the control of the execution.
The break statement
The break statement is used to prematurely terminate the execution of a while loop. A break can occur anywhere in the loop body, once it is encountered the loop immediately comes to a stop and control is passed to the statement immediately following the loop.
The continue statement
The continue statement is used to skip the current iteration of a loop and continue with the next iteration. Once a it is encountered the loop immediately starts the next iteration without executing the remaining statements.
The else statement
It is possible to use else statements with loops, the statements of the else block are only executed if the while loop terminates successfully i.e without encountering any break statement.