Does Python Have a "do...while" Loop?

Find out if there's a "do...while" loop in Python

Python does not have a built-in "do...while" loop. However, you can use a while loop to emulate the behavior of a "do...while" in the following way:

condition = True

while condition:
  # do something
  condition = False

This would run the loop at least once, and continue till the "condition" is False. For example:

condition = True
i = 0

while condition:
    print(i)
    i += 1
    condition = i < 5

# output: 0 1 2 3 4

As an alternative, you could also do the following:

while True:
    # do something
    if fail_condition:
        break

This would run the loop at least once, and break when the if condition is met. For example:

i = 0

while True:
    print(i)
    i += 1
    if i == 5:
        break

# output: 0 1 2 3 4

Hope you found this post useful. It was published . Please show your love and support by sharing this post.