Python While Loop Tutorial – POFTUT

Python While Loop Tutorial


Python provides different type of looping mechanism. while is the most popular one after for loops. while loops generally used to iterate and check given condition result as boolean. If the condition is True the loop will resume but if the condition is False the while loop will be ended.

Syntax

Here is the syntax of while loop in Python.

while (CONDITION):
   STATEMENT

Loop

In this part we will look simple but instructive example in order see how while loop works. We will create a int variable count and we will count up to 10 . When the counter is 10 we will stop the while loop.

counter=0 
while counter < 10: 
   print(counter) 
   counter = counter+1
Loop
Loop

Infinite Loop

General development problems will generally requires to stop loops if given condition is met. But some time we may need to run loops forever unless it is ended externally like killing the process. In this example we will look infinite loop . We will put True boolean value to the while condition part like below.

while (True): 
   print("I will run forever")
Infinite Loop
Infinite Loop

Else Statement with While

else is a python statements which is used with if-elif-else statements. But there is also use case with while statement too. else  statement executed when while loop is ended with a False condition. In this example we use previous example but also add else statement and print "Previous while loop ended" .

counter=0                      
while counter < 10:            
   print(counter)              
   counter = counter+1         
else: 
   print("Previous while ended loop ended")
Else Statement with While
Else Statement with While

Premature Termination

While running while loops we may need to terminate the loop. There are different ways to terminate a loop. First one is we can change the condition of while loop but this can not be easy sometimes. Second one is better, more readable and practical way. We can end the loop with break keyword. break will stop the loop where it issued.

LEARN MORE  C - Arrays

In this example we will stop the loop if the counter is equal to 5  by issuing break keyword.

counter=0 
while counter < 10:    
   if(counter==5): 
      break 
   print(counter) 
   counter=counter+1
Premature Termination
Premature Termination

Leave a Comment