The while and do while loops are generally available in different programming languages.
- As such, the difference between while and do while loop is the do while loop executes the statements inside it at least once; even if the condition fails at the first iteration.
- 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:
int_a = 110 a_bool = True while a_bool or int_a <= 100: a_bool = False print ("The value of variable = " ,int_a) int_a = int_a + 10 #As doing the same stuff using Normal while loop int_b = 110 while int_b <= 100: print (int_b) int_b = int_b+10
Output:
You can see, even the initial value of the variable int_a is 110, the statement inside the while loop is 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.
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:
int_y = 55 chk_cond = True while chk_cond: print ("The int_y = " ,int_y) int_y = int_y + 5 chk_cond = int_y <= 50
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 the condition was false.
However, despite 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 of using the while loop for do-while purposes is using the false condition with the break statement. Have a look:
#A demo of Python do while trick a = 55 while True: print ("The value of a = " ,a) a = a+5 if a > 50: break #Normal while loop b = 55 while b <= 50: print (b) b = b+5
Result: