Python While Loop Tutorial

Python provides the popular for and while loops. Even it is not popular as for loop the while loop is also used for different cases. Python while loop is very simple and easy to use where the while loop continues unless the given while loop condition is True. The while loop also provides the break statement, continue statement, and else statements for different cases.

while Loop Syntax

The while loop syntax is like below for the Python.

while CONDITION:
   CODE
  • CONDITION is the the condition we want to check and the while loop will continue as it is True. The CONDITION is checked in every step.
  • CODE is executed unless the CONDITION is true and the loop continue.

while Loop Example

We will set the variable named a and then set the initial value as 1. Then we will check the value whether it is less than 10 and execute the while code block which will print the a's current value and then increase a value by one.

a = 1

while a < 10:
   print(a)
   a += 1

The output will be like below. We can see that the output starts from 1 and then continue to the 9. When the a is increased into 10 the condition will not met because it is not less then 10.

1
2
3
4
5
6
7
8
9

Break while Loop

Even the while loop provides a condition which is used to control the while loop there is also break statement which can be used to exit from the while loop. Below we will check if the variable a is equal to 5 we will exit or break from the while loop.

a = 1

while a < 10:
   print(a)
   a += 1
   if(a==5):
      break

The output will be like below.

1
2
3
4

Skip Next Step with Continue in while Loop

The while loop code block is executed in every iteration or step. But if we need to skip some steps of some part of the while code block for specific conditions the continue statement. The continue statement will skip to the next step or iteration without ending the while loop. In the following example, we will skip if the value can be divided into 3 without a remaining.

a = 1

while a < 10:
   a += 1
   if(a%3==0):
      continue
   print(a)
   

Else Statement of while Loop

Differently from other programming languages while loop implementation the Python provides the else statement for the while loop. The else statement of the while loop is used when the loop ended with the condition is not True we can execute a code. In the following example when the while loop ends we will print some message to the screen.

a = 1

while a < 10:
   print(a)
   a += 1
else:
   print("The counting process reached to 10")

The output will be like below where the else statement code block is executed after the while loop code block.

1
2
3
4
5
6
7
8
9
The counting process reached to 10

Leave a Comment