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:

Syntax:
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.

ExampleEdit & Run

Use while loop to print integers from 0 to 9

i = 0
while i < 10:
    print(i)
    i += 1
Output:
0123456789[Finished in 0.010650652926415205s]

The various parts of the while loop are as shown below:

an image showing the parts of a while loop

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.

An image showing the flow chart of a while loop.

Let us look at another example.

ExampleEdit & Run

Use while loop to print values from 9 to 0


i = 9
while i >= 0:
    #The body of the loop
    print(i)
    i -= 1
Output:
9876543210[Finished in 0.010046086041256785s]

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 becomes less than or equal to 0, the condition fails and, therefore, the loop terminates. 
A flow chart showing a decrementing while loop

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.

ExampleEdit & Run

Use while loop to iterate a list

#the list
L = ['Python', 'Java', 'C++', 'C#', 'Kotlin', 'Swift', 'Ruby']

index = 0
while index < len(L):
   print(L[index])
   #increment the index
   index += 1
Output:
PythonJavaC++C#KotlinSwiftRuby[Finished in 0.010337691055610776s]

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.

ExampleEdit & Run

Use while loop with sets

#the list
S = {'Python', 'Java', 'C++', 'C#', 'Kotlin', 'Swift', 'Ruby'}

while len(S) != 0:
   print(S.pop())
Output:
C++RubyC#KotlinSwiftPythonJava[Finished in 0.010906605049967766s]

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

ExampleEdit & Run

Multiple conditions in while loops

nums = [i for i in range(10)]

i = 0
j = 10

while i <= 5 and j >= 5: 
    print(i, j) 
    i += 1
    j -= 1
Output:
0 101 92 83 74 65 5[Finished in 0.010718279983848333s]

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.

ExampleEdit & Run

Use the break statement to terminate a while loop

i = 0

while i < 10:
    print(i)
    if i == 5:
       break
    i += 1
Output:
012345[Finished in 0.011501987930387259s]

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.

ExampleEdit & Run

Use the continue statement to skip over even numbers.

i = 0

while i < 10:
    if i % 2 == 0:
       i += 1
       continue

    print(i)
    i += 1
Output:
13579[Finished in 0.010327208787202835s]

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.

ExampleEdit & Run

else statement with while loops   

i = 0
while i < 10:
    print(i)
    i += 1
else:
    print('Finished!')
Output:
0123456789Finished![Finished in 0.00994819588959217s]