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):

// 打印小于 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 is also a common control loop. Way.

Their relationship seems to be a bit like the difference between i++and ++ioperations 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 experience is repeatedly executed many times, but do {...} while (0) it only needs 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) combined with the use of break, a very elegant jump control effect can also be achieved.

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 {
  // 执行步骤 1 
  if (条件1失败) {
    break;
  }
  // 执行步骤 2 
  if (条件2失败) {
    break;
  }
  // 执行步骤 3 
  if (条件3失败) {
    break;
  }
} while(0);
// 执行步骤 4
// 执行步骤 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 low memory era in the past, 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 achieve  do {...} while (0) the jump control effect.

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:

Reply by Guido

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.

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 sum up a little, do-while, as a common looping structure, has played a role in other languages, and it has even developed a do {...} while (0) typical usage. However, several problems that do-while can solve are either in Python or not. Does not exist (macro definitions, assembly instructions), or there is a more suitable and low-cost implementation (jump control).

 [python learning] Python learning
partners, welcome to join the new exchange [Jun Yang]: 1020465983
to discuss programming knowledge together, become a great god, there are software installation packages, practical cases, learning materials in the group

Guess you like

Origin blog.csdn.net/weixin_56659172/article/details/124361234