Last Updated: June 06, 2019
· saji89

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;

  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:
    i = i + 1
    if(i > 3):

6 Responses
Add your response


Sorry, but it is not Python code, it is C...
I know Python and C,
There are not "{", "}" in Python and "if" writes without "(" and ")", also Python has not ";" in the end of line, Python has not "%d", "\n", "%f" and others... but all it has C.

2 months ago ·
about 2 months ago ·

nice information. thats what i was looking for :)

about 2 months ago ·

Thanks, Saji for this little help. Keep it up, sir. https://www.cdhpl.com/how-to-use-bzip2-to-compress-files/

about 1 month ago ·

why i m getting an error running this code https://freegiftcardsgen.com/

29 days ago ·

Nice, that worked like a charm :) https://www.9apps.red/

7 days ago ·