Python provides the for and while loop in order to iterate a given list, iterable object, or for conditions. Even though it is not much popular as for loop while loop is also used for different cases. Popular programming languages like C, C#, and Java provide the do-while loop but Python does not provide the do-while loop. So if Python does not provide the do-while loop how can we emulate it?
Emulate do-while Loop In Python
The do-while loop works like this. First, the do part of the do-while loop should be executed before the condition check. So we will set the while condition as True which will continue forever. But how can define the end condition for this do-while loop? We will use if conditional inside the while loop which will execute the break statement that will end the while loop.
a = 1
while True:
print(a)
a += 1
if (a>=10):
break
The output will be like the below. We can see that the variable “a” is printed in every step. Then the value of the “a” is checked with the “if” statement which is equal to the “do” for the “do-while” statement. If the variable “a” value meets the specified condition the “break” statement is executed.
1 2 3 4 5 6 7 8 9
while vs do-while
The while
statement is used to iterate for the specified condition. The while statement simply executes every iteration and then checks the condition. The do-while
loop first executes body and then checks the condition. The difference between “do” and “do-while” is the check condition step.