What is do while loop?

The while and do while loops are generally available in different programming languages. Python also has while loop, however, do while loop is not available.

As such, the difference between while and do while loop is the do while loop executes the statements inside it at least once; even the condition fails at first iteration.

“do while” Example 1 Example 2

There may be scenarios when you will need to execute a block of code as using the while loop, so how you can do this in Python?

In this tutorial, I will show you a few code samples as using the while loop while it fulfills the purpose of do while i.e. even if the condition fails at first check, the statements inside the while loop will execute.

An example of Python “do while” loop

In this example, a variable is assigned an initial value of 110  i.e. int_a = 110. The condition in the while loop is to execute the statements inside as long as the value of int_a is less than or equal to 100. In each iteration, the value of the variable is increased by 10. So, the condition fails on the first check and see how it outputs:

See online demo and code

 

Python do while

You can see, even the initial value of the variable int_a is 110, the statement inside the while loop executed. This is what a do while loop should have done.

The second piece of code shows using the while loop normally and in the output, you can see no statement executed as the condition was false up front.

Second trick of using do while loop

The intended purpose of executing the statements in the while loop at least once can also be accomplished by using this technique as well. A Boolean variable is declared and assigned a True value initially (outside of while loop).

Use that variable in the while loop and write the statements inside (or perform the desired action inside the while loop). Finally, assign the condition of the “do while” loop that you require to that Boolean variable. Have a look:

See online demo and code

do while way

The scenario of the do while loop was to execute the statements as long as the variable int_y value is less than or equal to 55. The initial value is set as 55 so condition was false.

However, in spite of the greater value, the print statement executed and displayed the value of int_y which is 55 (the goal of do while loop).

Third technique – Python do while loop

The third technique as using the while loop for do while is using the false condition with the break statement. Have a look:

See online demo and code

 

do while break

 

*Note: All these tricks are inspired by the solutions present in StackOverflow.