Difference between while loop and do while loop in python

Submitted 3 years, 2 months ago
Ticket #361
Views 326
Language/Framework Python
Priority Medium
Status Closed

These loops are really confusing ......

Any explanation with example will be of great help...

Help me out please

Submitted on Feb 26, 21
add a comment

1 Answer

Verified

In while loop the condition is checked before the block of code is executed
In do .. while loop the condition is checked after the block of code is executed.

* In Python doesn't exist a do .. while loop, but you can emulate one

x = 0

print("WHILE RESULT:")

while x > 0:
    # block of code to be executed inside the loop
    print("It won't execute")
    x += 1
    # end of block
    
print("EMULATED DO .. WHILE RESULT:")
    
# since there is no do .. while loop in Python,
# you can emulate one like this:
while True:
    # block of code to be executed inside the loop
    print(f"This will print x: {x}")
    x += 1
    # end of block

    # condition checked at the end of a loop cycle
    if not x > 0:
        break
    # end of condition

I've added some comments inside the code, so you might be able to understand the logic

This example is in JavaScript:
 

let x = 0;

console.log("WHILE RESULT:");

while(x > 2) {
    console.log("It won't execute");
}
  
console.log("DO .. WHILE RESULT:");
    
do {
  
  console.log("Here x is " + x);
  x++
  
} while(x > 2);

Submitted 3 years, 2 months ago


Latest Blogs