程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Why doesnt Python design a do while loop structure?

編輯:Python

In some programming languages , for example C/C++、C#、PHP、Java、JavaScript wait ,do-while It's a basic circular structure .

Its core semantics is : Do it first Loop body code , Then do it again Conditional statements , If the conditional statement is judged to be true , Then continue to execute the loop body code , And execute the conditional statement again ; Until the conditional statement is judged as false , Then jump out of the loop structure .

The flow chart is as follows (Java Example ):

// Print less than 20 The number of
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 do-while structure ,“do” Not a valid keyword .

that , Why? Python Don't provide this grammatical structure , What are the design considerations behind this situation ?

Before I answer that question , Let's think again do-while What problems can grammar solve , Look at the benefits of using this structure ?

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

Its usage scenarios may not be many , however , With ordinary while Loop or for Circular syntax “ Preconditions ” Different thoughts , It embodies a kind of “ Conditional postposition ” Programming logic , It's also a common way to control loops .

Their relationship seems a bit like C/C++ In these languages i++ And ++i Differences in operation , On some special occasions , It may be more efficient .

In addition to this feature , The biggest application scenario of this structure is actually C/C++ In particular do {...} while (0) usage . This can be found in the source code of many open source projects , for example Linux、Redis as well as CPython Interpreter , wait .

The numbers in this 0 Represents a Boolean value False, It means that the loop will only execute once , Then jump out .

Isn't that weird ? So-called “ loop ”, Generally, it means that the program will be executed repeatedly many times , however ,do {...} while (0) But it only needs to be executed once , It seems a little redundant at first .

This writing method is mainly used in the definition of macro functions , It can solve the compilation problem of macro code blocks , Make the code reasonably partitioned according to our intention .

in addition ,do {...} while (0) combination break Use , It can also achieve a very elegant jump control effect .

In the following example , step 1、4 and 5 Requirements must be implemented , And steps 2 Depending on the steps 1 The results of the implementation of , step 3 It depends on step 2 The results of the implementation of .

do {
// Execution steps 1
if ( Conditions 1 Failure ) {
break;
}
// Execution steps 2
if ( Conditions 2 Failure ) {
break;
}
// Execution steps 3
if ( Conditions 3 Failure ) {
break;
}
} while(0);
// Execution steps 4
// Execution steps 5

In this scenario , We really only need to do it once in order .do-while The structure is very clear , Avoid the situation of multi-layer conditional nesting or setting many additional tags .

Last but not least , At the assembly level ,do-while Than while Closer to the logic of assembly language , Can save the use of instructions , In the past era of low memory , It can be regarded as an optimized writing method .

Analysis finished do-while After the benefits of , Let's go back to the subject :Python Why not design do-while What about circular grammar ?

First ,Python Too far from the underlying application programming , There is no need to consider the optimization of assembly instructions , meanwhile , It also does not involve the use of macros .

as for “ Preconditions ” and “ Conditional postposition ” The difference between , In fact, it doesn't have much impact , and , because Python Use simple and elegant indentation plus colon syntax to divide code blocks , Lead to literal translation do-while Grammar can look weird ( Be careful , Literal translation while There is nothing else after the condition ):

do:
pass
while False

Want to introduce new syntax features , Be sure to follow the established style and habits . Other languages do-while The structure translates directly into Python Words , Definitely not .

in fact , stay 2003 in , There is one PEP Propose to Python add do-while Grammar support :

PEP-315 Enhanced While Loop

The PEP It is proposed to add an optional do Clause , Support will while The loop expands like this :

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

This is not simply translated from other languages into Python, its while After the statement Python Indent usage , It will not cause the unexpected result of literal translation .

add while Optional that the loop itself already supports else Clause , therefore ,while The complete grammatical structure is like this :

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

(PS. In the next article in this series , We will explain why Python To support while-else grammar )

in other words , Keep the original while With the same loop syntax ,PEP-315 Propose to support in while Use an optional... Before do Clause .

do Clause will only execute once , When it appears break when , Then jump out of the whole do-while loop ; When do Clause continue when , Is out of do Clause , Enter while In the condition judgment of .

With do After clause , It's easy to do do {...} while (0) Jump control effect .

however , This PEP It was opposed by some core developers .

The objection is , There is no need to introduce new keywords and Syntax , The same function can be well realized only by using the existing syntax :

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

Python The father of Guido van Rossum Also disagree , What he said was :

Guido Reply to

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.

A simple translation , such do-while Grammar does not make Python More elegant and easy to use , Instead, it will produce reading / The burden of maintaining code understanding .

In terms of personal feelings , I also disapprove of introducing PEP-315 That's optional do-while grammar , Although it is better than the fixed form do-while The structure is more flexible and elegant .

Finally, to summarize ,do-while As a common circular structure , Play a role in other languages , It even developed do {...} while (0) Typical usage of , however ,do-while Several problems that can be solved are either in Python Does not exist in ( Macro definition 、 Assembly instruction ), Or there has been a more suitable and low-cost implementation ( Jump control ).

After reading this article , Do you have anything else to add ? Welcome to exchange and discussion .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved