Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no do while loop in python

Why doesn't Python have a 'do while' loop like many other programming language, such as C?

Example : In the C we have do while loop as below :

do {    statement(s); } while( condition ); 
like image 585
Bahubali Patil Avatar asked May 17 '16 16:05

Bahubali Patil


People also ask

Does Python have a do-while loop?

Python doesn't have do-while loop. But we can create a program like this. The do while loop is used to check condition after executing the statement. It is like while loop but it is executed at least once.

Why use for loop instead of while and do-while?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.

Do-while () loop is?

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.


2 Answers

There is no do...while loop because there is no nice way to define one that fits in the statement: indented block pattern used by every other Python compound statement. As such proposals to add such syntax have never reached agreement.

Nor is there really any need to have such a construct, not when you can just do:

while True:     # statement(s)     if not condition:         break 

and have the exact same effect as a C do { .. } while condition loop.

See PEP 315 -- Enhanced While Loop:

Rejected [...] because no syntax emerged that could compete with the following form:

    while True:         <setup code>         if not <condition>:             break         <loop body> 

A syntax alternative to the one proposed in the PEP was found for a basic do-while loop but it gained little support because the condition was at the top:

    do ... while <cond>:         <loop body> 

or, as Guido van Rossum put it:

Please reject the PEP. More variations along these lines won't make the language more elegant or easier to learn. They'd just save a few hasty folks some typing while making others who have to read/maintain their code wonder what it means.

like image 59
Martijn Pieters Avatar answered Oct 04 '22 09:10

Martijn Pieters


Because everyone is looking at it wrong. You don't want DO ... WHILE you want DO ... UNTIL.

If the intitial condition is true, a WHILE loop is probably what you want. The alternative is not a REPEAT ... WHILE loop, it's a REPEAT ... UNTIL loop. The initial condition starts out false, and then the loop repeats until it's true.

The obvious syntax would be

repeat until (false condition):   code   code 

But for some reason this flies over everyone's heads.

like image 34
Caleb Fuller Avatar answered Oct 04 '22 07:10

Caleb Fuller