Introduction

Do...while loops are an essential programming construct that executes a set of statements repeatedly as long as a given condition evaluates to true. In Python, there is no built-in do...while loop. However, we can easily imitate a do...while loop using other loop types and conditional statements. This tutorial will guide you through the concept of do...while loops and show you how to replicate their functionality in Python. So, let's dive into the world of looping in Python!

Table of Contents :

  • What is a do...while loop
  • do...while loop in Python

What is a do...while loop

  • Most of the programming languages support a do...while loop construct.
  • In a do..while loop the condition is evaluated at the end of the loop.
  • Hence the loop body is executed at-least once in case of do..while loop.
  • Basic syntax of do..while loop in other programming languages

do
  # While code block
while loop-condition

do...while loop in Python

  • Python do not have an in-built do..while loop construct.
  • We can mimic a do...while loop in python by using :
  • The syntax of the do...while imitation in Python is as follows : 

while True:
   # While code block

   # If condition to end the loop
   if condition
       break
       
       
  • Code Sample : 

index = 2
while True:
	sqr = index ** 2
	print(f"Value of index = {index}")
	print(f"Square of index = {sqr}")
	print()
	index += 1

	if index == 5:
	    break
	

# Output

# Value of index = 2
# Square of index = 4

# Value of index = 3
# Square of index = 9

# Value of index = 4
# Square of index = 16


Prev. Tutorial : While...else loop

Next Tutorial : Break statement