Difference between while loop and do while loop in python

Submitted 6 months, 3 weeks ago
Ticket #361
Views 102
Language 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 6 months, 3 weeks ago


Wanna Post Ad?
Reach a large group of audience by posting an ad about your business here. For more details
Drop us a Message