Do While loop Syntax in Python

Python doesn’t have a built-in do while loop, but a similar behavior can be achieved using a while loop with a condition check after the code block.

Syntax:

while True:
# Code block to be executed at least once
if not condition:
break

Explanation of the Syntax:

  • Python doesn’t have a built-in do while loop construct.
  • However, a similar behavior can be achieved using a while loop with a conditional break statement.
  • The loop is initiated with a condition that is always true (while True:).
  • Inside the loop, the code block is executed at least once.
  • After executing the code block, an if statement checks the condition.
  • If the condition is not met (not condition), the loop is terminated using the break statement.

Implementation of Do While Loop Syntax in Python:

Python3




i = 0
while i < 10:
    print(i, end=" ")
    i += 1


Output

0 1 2 3 4 5 6 7 8 9 

Do While loop Syntax

Do while loop is a control flow statement found in many programming languages. It is similar to the while loop, but with one key difference: the condition is evaluated after the execution of the loop’s body, ensuring that the loop’s body is executed at least once.

Table of Content

  • Do While loop Syntax in C/C++
  • Java Do While loop Syntax
  • Do While loop Syntax in Python
  • Do While loop Syntax in C#
  • Do While loop Syntax in JavaScript

The syntax for a do while loop varies slightly depending on the programming language you’re using, but the general structure is similar across many languages.

do {
// Code block to be executed at least once
// This block will execute at least once
} while (condition);

Here’s a basic outline:

  1. Initialization: Initialize any loop control variables or other necessary variables before entering the loop.
  2. Do While Loop Structure: The loop consists of two main parts: the “do” block and the “while” condition.
    • The “do” block contains the code that will be executed at least once, regardless of the condition.
    • The “while” condition specifies the condition that must be true for the loop to continue iterating. If the condition evaluates to true, the loop will execute again. If it evaluates to false, the loop will terminate.
  3. Loop Execution: The loop executes the code inside the “do” block, then evaluates the “while” condition.
    • If the condition is true, the loop repeats, executing the code block again.
    • If the condition is false, the loop terminates, and control passes to the code following the loop.

Similar Reads

Do While loop Syntax in C/C++:

Syntax:...

Java Do While loop Syntax:

...

Do While loop Syntax in Python:

...

Do While loop Syntax in C#:

Syntax:...

Do While loop Syntax in JavaScript:

...