为什么python中没有do while循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37281553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:10:10  来源:igfitidea点击:

Why there is no do while loop in python

pythonloopsdo-while

提问by Bahubali Patil

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

为什么 Python 不像许多其他编程语言(例如 C)那样具有“do while”循环?

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

示例:在 C 中,我们有如下 while 循环:

do {
   statement(s);
} while( condition );

回答by Martijn Pieters

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

没有do...while循环,因为没有很好的方法来定义一个适合statement: indented block所有其他 Python 复合语句使用的模式的循环。因此,添加此类语法的建议从未达成一致。

Nor is there really any needto 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 conditionloop.

并具有与 Cdo { .. } while condition循环完全相同的效果。

See PEP 315 -- Enhanced While Loop:

参见PEP 315——增强的 While 循环

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>

被拒绝 [...] 因为没有出现可以与以下形式竞争的语法:

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

为基本的 do-while 循环找到了 PEP 中提议的语法替代方案,但它获得的支持很少,因为条件位于顶部:

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

or, as Guido van Rossum put it:

或者,正如Guido van Rossum 所说

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.

请拒绝 PEP。沿着这些路线的更多变化不会使语言更优雅或更容易学习。他们只是让一些匆忙的人打字,而让其他必须阅读/维护他们的代码的人想知道这意味着什么。