Python 6: While Loops

Hi guys,

Welcome to my new post on Python. Its been quite a long time since I wrote about Python. I plan to write series of posts on core Python that’ll cover from basics to OOP. These posts will be useful for someone who has just started learning Python. These posts are based on the training I had provided on core Python. There may be something missing in these articles, please feel free to comment if you think anything that should be added is missing.

Please feel free to access all Python posts here


Just like for loops discussed here, while loops are also a form of programming constructs to repeat some tasks. Unlike for loop that needed the number of iterations or some range of values to iterate, while loops iterate on the basis of condition. Code in while block will execute until the condition provided is True and will stop once it is False. One example where while loop may be used is in simulations where the condition is the threshold that should be matched, code will repeat until the threshold is fulfilled. e.g: loop until error margin is not less than 0.05 or stop loop once error margin reaches 0.05.


while expression:

Here code_to_execute will run until expression is True and will stop executing once expression evaluates to false.

counter = 0
while counter < 3:
   print('loop {0}'.format(counter))
   counter += 1

Above code will print the following

loop 0

loop 1

loop 2

As you can see, loop will run until counter is less than 3 and prints counter.

Nested While Loop

Just as in for loop, while loop also supports nested loop i.e. while loop inside while loop.

A = [[1, 2, 4],[6, 7, 8]]
B = [[4, 8, 5],[8, 12, 0]]
C = [[0,0,0],[0,0,0]]
row = 0
while row < 2:
    column = 0
    while column < 3:
        C[row][column] = A[row][column] + B[row][column]
        column +=1
    row += 1

In the above code two matrices are added using nested while loop. Outer loop iterates through rows and inner loop iterates through columns to access the elements of matrices and add them.

Loop control statements work in the same way they do in for loop.

I hope this post was useful for you to learn while loops. Please feel free to let me know if you think I’m missing something here and should add.

Also please leave comments for any queries or suggestions.

I’ll see you in the next one. Cheers 🙂

132 total views, 2 views today

Leave a Reply

Your email address will not be published. Required fields are marked *