Python while loop:

The while loop is used to repeatedly execute the block of statement as long as an expression is true. In other words, it constantly tests the expression and, if it is true, executes the first suite or block of statements. However, if the expression is false, the suite of the else clause is executed if available and the loop terminates.

Syntax :

The signature for the while statement is as shown below. Here, else block is optional.

while assignment_expression :
     suite/block of statements
[else :
     suite/block of statements]

Flow diagram – while statement :

Flow diagram - while statement

Python while statement Examples:

Example 1: In this example, we will print numbers from 100 to 104. Once the condition of while is false, it executes the block of statements in the else clause.

#Initializing
i=100
# Using while statement with else clause and printing
while i < 105:
   print(i)
   i=i+1
else:
print("Reached at end of list")

Output

100
101
102
103
104
Reached at end of list

Example 2: In this case, we will print odd numbers less than 10 using a while loop.

#Initializing
i=1
while i<10:
   if i%2==0:
      i=i+1
      continue
else:
    print(i)
    i=i+1

Output

1
3
5
7
9

Example 3: In this example, We will print the elements of the list using a while loop.

#Initializing
l=[100,110,210,310,410]
i=0
# Using while statement with else clause and printing
while i < len(l):
    print(l[i])
    i=i+1
else:
    print("Reached at end of list")

Output

100
110
210
310
410
Reached at end of list

References

Happy Learning 🙂