Why doesn’t Python design a do-while loop structure?

In some programming languages, such as C/C++, C#, PHP, Java, JavaScript, etc., do-while is a basic looping construct.

Its core semantics are: execute the loop body code first, then execute the conditional statement once, if the conditional statement is judged to be true, continue to execute the loop body code, and execute the conditional statement again; until the conditional statement is judged to be false, then jump out of the loop structure .

The flowchart is as follows (Java example):

 // print numbers less than 20 public class Test {    public static void main(String[] args){       int x = 10;       do {          System.out.print("value of x : " + x );          x++;          System.out.print("\n");       } while(x < 20);    } }  

Python does not support the do-while construct, and “do” is not a valid keyword.

So why doesn’t Python provide this syntax structure, and what are the design considerations behind this status quo?

Before answering this question, let’s think a little more about what the do-while syntax can solve, and see what benefits can be gained from using this structure?

The most obvious benefit is that the do-while syntax guarantees that the body of the loop will be executed first.

Its usage scenarios may not be many, but, unlike the ” precondition ” idea of ​​ordinary while loop or for loop syntax, it embodies a ” conditional post ” programming logic, and it is also a common control loop. Way.

Their relationship seems to be a bit like the difference between i++ and ++i operations in languages ​​such as C/C++, and may be more efficient in some special cases.

In addition to this feature, the biggest application scenario of this structure is actually the special do {...} while (0) usage in C/C++. This can be found in the source code of many open source projects, such as Linux, Redis, and the CPython interpreter, to name a few.

The number 0 here represents the boolean value False, which means that the loop will only execute once and then jump out.

Isn’t this spelling weird? The so-called “loop” generally means that the program body is repeatedly executed many times, but do {...} while (0) only needs it to be executed once, which seems a bit redundant at first.

This writing method is mainly used in the definition of macro functions, which can solve the problem of compiling macro code blocks, so that the code can be divided into reasonable blocks according to our intention.

In addition, do {...} while (0) can be used in combination with break to achieve a very elegant jump control effect.

In the example below, steps 1, 4, and 5 are required to be executed, while step 2 depends on the result of step 1, and step 3 depends on the result of step 2.

 do {   // execute step 1    if (condition 1 failed) {     break;   }   // execute step 2    if (condition 2 failed) {     break;   }   // execute step 3    if (condition 3 failed) {     break;   } } while(0); // execute step 4 // go to step 5  

In this scenario, we really only need to do it once in order. The do-while structure is very clear and avoids situations where multiple levels of conditional nesting or many additional flags are set.

Finally, at the assembly level, do-while is closer to the logic of assembly language than while, which can save the use of instructions. In the past low memory era, it can be regarded as an optimized writing method.

After analyzing the benefits of do-while, let’s go back to the topic: Why doesn’t Python need to design do-while loop syntax?

First of all, Python is too far away from low-level application programming to consider the optimization of assembly instructions, and at the same time, it does not involve the use of macros.

As for the difference between “conditional pre-condition” and “conditional post-condition”, it doesn’t have much impact. Moreover, since Python uses concise and elegant indentation and colon syntax to divide code blocks, the literal translation of do-while syntax looks like would be weird (note that there is nothing after the condition of the literal while):

 do:     pass while False  

If you want to introduce new grammatical features, you must follow the established style habits. Do-while constructs in other languages ​​are definitely inappropriate when translated literally into Python.

In fact, in 2003, there was a PEP proposal to add do-while syntax support to Python:

PEP-315 Enhanced While Loop

This PEP proposes to add an optional do clause to support expanding the while loop to look like this:

 do:     <setup code> while <condition>:     <loop body>  

This is not simply translating from other languages ​​to Python, it retains Python’s indentation usage after the while statement, and does not cause obtrusive results in literal translation.

With the optional else clause already supported by the while loop itself, the full syntactic structure of while is as follows:

 while_stmt : ["do" ":" suite]             "while" expression ":" suite             ["else" ":" suite]  

(PS. In the next article in this series, we will explain why Python supports the while-else syntax)

That is, while keeping the original while loop syntax unchanged, PEP-315 proposes to support the use of an optional do clause before while.

The do clause will only be executed once. When break appears in it, it will jump out of the entire do-while loop; when continue appears in the do clause, it will jump out of the do clause and enter into the conditional judgment of while.

With the do clause, it is easy to realize the jump control effect of do {...} while (0) .

However, this PEP was opposed by some core developers.

The objection is that there is no need to introduce new keywords and syntax, and the same functionality can be implemented just fine using the existing syntax:

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

Guido van Rossum, the father of Python, also disagreed. His original words were:

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 hastyfolks some typing while making others who have to read/maintain their code wonder what it means.

Simply translated, this do-while syntax does not make Python more elegant and easy to use, but creates an comprehension burden of reading/maintaining code.

Personally, I also disapprove of introducing the optional do-while syntax of PEP-315, although it is a bit more flexible and elegant than the fixed-form do-while construct.

Finally, to summarize a little, do-while, as a common looping structure, has played a role in other languages, and it has even developed the typical usage of do {...} while (0) . However, do-while can Several of the problems solved either do not exist in Python (macro definitions, assembly instructions), or there are more suitable and low-cost implementations (jump control).

After reading this article, do you have anything else to add? Exchanges and discussions are welcome.

If you are interested in topics related to Python language design, please subscribe to the “Why Python” series of articles on Github (https://github.com/chinesehuazhou/python-whydo )

Related reading:

Why does Python have a strange “…” object?

Why do Python functions return None by default?

Why did the father of Python dislike lambda anonymous functions?

Why is inheriting Python built-in types problematic? !

Why does Python recommend snake-like nomenclature?

The text and pictures in this article are from InfoQ

loading.gif

This article is reprinted from https://www.techug.com/post/why-doesn-t-python-design-a-do-while-loop-structure.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment