How to Write a do-while Like Loop in Python

Published on Aug. 22, 2023, 12:20 p.m.

Python does not have a built-in do-while loop. However, you can achieve similar functionality with a while loop that always runs at least once, and then checks the loop condition at the end of each iteration. Here is an example:

while True:
    # code to execute goes here
    if not condition:
        break

This loop will run the code block at least once, and then check the loop condition at the end of each iteration to determine whether to continue or break out of the loop. The True condition will cause the loop to run indefinitely until the break statement is encountered.

Alternatively, you can create a function that performs the desired action at least once, and then checks the loop condition at the end of each iteration. Here is an example:

def do_while(action, condition):
    action()
    while condition():
        action()

You can then use this function to perform a do-while-like loop by passing in a function that performs the desired action, and a function that evaluates the loop condition.

Tags: