q_rd1q
Last Updated: February 17, 2018
·
14.01K
· saji89
Afc9686c3ca7e7473b2a7183a53a4a60

Emulate do-while loop in Python

At times we encounter situations where we want to use the good old do-while loop in Python. The importance of a do-while loop is that it is a post-test loop, which means that it checks the condition only after is executing the loop block once. Though Python doesn't have it explicitly, we can surely emulate it.

General structure for a do-while loop:

do {

     loop block

} while (condition);

loop block consists of the statements/program fragment you want to execute in loop.

A do-while example from C:

int i = 1;

do{
  printf("%d\n", i);
  i = i + 1;
} while(i <= 3);

Emulating do-while in Python

We can write the equivalent for the do-while in the above C program using a while loop, in Python as follows:

i = 1

while True:
    print(i)
    i = i + 1
    if(i > 3):
        break
Say Thanks
Respond