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
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.