Python,为什么是 elif 关键字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3742580/
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-18 12:30:38  来源:igfitidea点击:

Python, why elif keyword?

pythonkeyword

提问by raisyn

I just started Python programming, and I'm wondering about the elifkeyword.

我刚开始 Python 编程,我想知道elif关键字。

Other programming languages I've used before use else if. Does anyone have an idea why the Python developers added the additional elifkeyword?

我之前使用过的其他编程语言使用else if. 有谁知道为什么 Python 开发人员添加了附加elif关键字?

Why not:

为什么不:

if a:
    print("a")
else if b:
    print("b")
else:
    print("c")

采纳答案by Daniel A. White

Most likely it's syntactic sugar. Like the Wendof Visual Basic.

很可能是语法糖。就像WendVisual Basic 的一样。

回答by Adam Lear

Far as I know, it's there to avoid excessive indentation. You could write

据我所知,这是为了避免过度缩进。你可以写

if x < 0:
    print 'Negative'
else:
    if x == 0:
        print 'Zero'
    else:
        print 'Positive'

but

if x < 0:
    print 'Negative'
elif x == 0:
    print 'Zero'
else:
    print 'Positive'

is just so much nicer.

真是太好了。



Thanks to ignfor the docsreference:

感谢ign提供文档参考:

The keyword elifis short for 'else if', and is useful to avoid excessive indentation.

关键字elif是“else if”的缩写,可用于避免过度缩进。

回答by bobince

Python inherits this from Perl, where it's called elsif.

Python 从 Perl 继承了它,在那里它被称为elsif.

In Python's case, else ifas two separate constructs like it is in C-like languages would be quite ugly as you'd have to have else: if:with two indenting levels.

在 Python 的情况下,else if像 C 类语言中的两个独立构造将非常丑陋,因为您必须else: if:具有两个缩进级别。

It's arguable whether special-casing the two keywords together would be better (so making else ifa single construct, like the not inoperator.

将两个关键字的特殊大小写放在一起是否更好是有争议的(因此制作else if单个构造,如not in运算符。

PL/SQL also has elsif, and the C preprocessor has it spelled elif.

PL/SQL 也有elsif,C 预处理器将其拼写为elif

回答by Lie Ryan

To avoid brace^H^H^H^H^Helse if war.

避免大括号^H^H^H^H^Helse 如果War。

In C/C++ where you have an else if, you can structure your code in many different styles:

在具有 的 C/C++ 中else if,您可以以多种不同的样式构建代码:

if (...) {
    ...
} else if (...) {
    ...
}


if (...) {
    ...
} 
else if (...) {
    ...
}

if (...) {
    ...
} else 
if (...) {
    ...
}

// and so on

by having an elifinstead, such war would never happen since there is only one way to write an elif. Also, elifis much shorter than else if.

通过elif替代,这样的War永远不会发生,因为只有一种方法可以编写elif. 此外,elifelse if.

回答by Gordon Gustafson

That's just the way it is. Javascriptuses else if, phpuses elseif, perluses elsif, the C preprocessor and python use elif. None of them are wrong, they just choose slightly different syntax to do the same thing. :D

就是那样子。Javascript使用else ifphp使用elseifperl使用elsif,C 预处理器和 python 使用elif。他们都没有错,他们只是选择稍微不同的语法来做同样的事情。:D

回答by masterLoki

elif is some sort of replacement for switch in other languages but with more power

elif 是其他语言中 switch 的某种替代品,但功能更强大

for example in C you write

例如在 C 中你写

switch (number){
 case 1:
   doA()
   break;
 case 2:
   doB()
   break;
 case N:
   doN()
   break;
 default:
   doSomethingElse()
   break;
}

in Python you write

在 Python 中你写

if number == 1: doA()
elif number == 2: doB()
elif number == N: doC()
else: doSomethingElse()

As you see elifis more powerful since you can put more complex statements than in a switch, plus avoid nesting if/elsestatements

正如您所见,elif它更强大,因为您可以放置​​比 switch 更复杂的语句,并且避免嵌套if/else语句

回答by Eddy Mulyono

I find them helpful to help differentiate the "else-if"s from the "final else".

我发现它们有助于区分“else-if”和“final else”。

回答by Ben

Languages with C-like syntax get else iffor free without having to implement it at all.

具有类似 C 语法的语言可以else if免费获得,而根本无需实现它。

The reason is that in that syntax control structures simply operate on the next statement, which can be a compound statement enclosed in braces if necessary (e.g. { x += 1; y += 1 }).

原因是因为语法控制结构只是对下一个语句进行操作,如果需要,它可以是用大括号括起来的复合语句(例如{ x += 1; y += 1 })。

This means that once you've implemented ifand else, else ifjust falls out of the grammar of the language naturally for free, with no further implementation effort. To see why, have a look at this:

这意味着一旦你实现了ifand elseelse if就自然而然地脱离了语言的语法,无需进一步的实现工作。要了解原因,请查看以下内容:

if (condition) {
    if_body();
} else if (another_condition) {
    else_if_body();
} else {
    else_body();
}

This looks like an ifwith an else ifand an elseattached, each applied to a compound statement. But in fact it's not. This is actually two separate ifstatements, each with exactly one elsecase; the second ifstatement is inside the body of the elseof the first ifstatement.

这看起来像一个if带有一个else if和一个else附加的,每个都应用于一个复合语句。但事实上并非如此。这实际上是两个单独的if语句,每个语句都有一个else案例;第二个if语句else在第一个if语句的主体内。

else if { ... }is really parsed as elseapplied to the next statement, which is an ifstatement (applied to the compound statement { else_if_body(); }. Then the final elsebinds to the immediately preceding if, which is the second one.

else if { ... }真正被解析为else应用于下一个语句,它是一个if语句(应用于复合语句{ else_if_body(); }。然后最后一个else绑定到紧接在前的if,这是第二个。

Here's the same thing written more in line with how it's parsed1:

这是更符合解析方式的相同内容1

if (condition) {
    if_body();
} else {
    if (another_condition) {
        else_if_body();
    } else {
        else_body();
    }
}

But it turns out that if the language did directly implement else ifas a first-class option for ifstatements, it would behave exactlythe same as the second independent ifstatement inside the elseof the first! So there's no need to bother implementing else ifat all; language implementers get else iffor free with this style of syntax, once they've implemented ifand else.

但事实证明,如果语言确实直接实现else ifif语句的一流选项,它的行为将与第一个独立语句中的第二个独立语句完全相同!所以根本不需要费心去实施;语言的实现得到免费的这种风格的语法,一旦他们已经实现和。ifelseelse ifelse ififelse

Python's syntax doesn't allow this freebie.

Python 的语法不允许这种免费赠品。

Programmers of C-style syntax can thinkin terms of else ifeven though the language only has ifwith exactly zero-or-one else, but only because they can write code like my first example that is formatted in a way that looks different to a human reader than it does to the compiler.

C风格的语法的程序员可以想到来讲else if,即使语言只if用准确的零或一else,但只是因为他们可以写这样的被格式化的方式,我的第一个示例代码,看起来对人类读者不同于它对编译器起作用。

Python, OTOH, uses indentation to indicate block structure, which forces the block structure to look the same to a human reader as it does to the interpreter2. Once you've got ifand elsein Python-style syntax, programmers could still write code that behavesidentically to an else-if, by putting a second ifstatement inside the elseof a first. But that comes out looking like this:

Python,OTOH,使用缩进来表示块结构,这迫使块结构在人类读者看来与解释器2 相同。一旦你得到了ifelse在Python风格的语法,程序员仍然可以写代码的行为等同于其他假设,通过把第二个if语句中的else一首。但这看起来像这样:

if condition:
    if_body()
else:
    if another_condition:
        else_if_body()
    else:
        else_body()

This looks ugly, and is much more complex to think in terms of than an else-if chain once you get more than 1 or 2 else-ifs. So it's worth adding in an explicit language feature to get back the ability to think in terms of else-if. Even though it technically makes the language more complex, it actually makes thinkingin terms of the language simpler, so it's good complexity; with a manually constructed chain of nested ifs inside elses the reader has to manually read all the code and verify that every elseexcept the last contains exactly one ifstatement and nothing else, in order to conclude that the whole sequence is equivalent to a linear chain of conditions checked in order, with some code to execute for the first check that succeeds.

这看起来很难看,而且一旦你得到 1 或 2 个以上的 else-if,就比 else-if 链要复杂得多。因此,值得添加一个明确的语言功能,以恢复根据 else-if 进行思考的能力。尽管它在技术上使语言变得更复杂,但它实际上使从语言方面的思考变得更简单,因此它的复杂性很好;使用ifs 内部嵌套的手动构建的s链,else读者必须手动阅读所有代码并验证else除了最后一个之外的每个代码都只包含一个if语句而没有其他任何内容,以便得出整个序列等价于线性条件链的结论按顺序检查,并在第一次成功检查时执行一些代码。

So then. We've seen that languages with C-like syntax might as well go with else if, because they get it for free. That's the reason why that exists. Languages with Python-like syntax have to explicitly do something to get a construct that can be used as an else-if. Why did they choose elif? It's arbitrary; you'd have to actually ask the people who made the decision.

那么。我们已经看到类似 C 语法的语言也可以使用else if,因为它们是免费的。这就是它存在的原因。具有类似 Python 语法的语言必须明确地做一些事情来获得一个可以用作 else-if 的构造。他们为什么选择elif?它是任意的;你实际上必须询问做出决定的人。

However Python didn't invent elif, it was around in other languages long before Python existed. So I would guessthat when they had to implement an explicit else-if construct they simply picked one that programmers were already familiar with.

然而 Python 并没有发明elif,它早在 Python 出现之前就已经在其他语言中出现了。所以我猜想,当他们必须实现一个明确的 else-if 结构时,他们只是选择了一个程序员已经熟悉的结构。



1Technically, this is how people who are REALLY serious about always using braces with control structures should write their code. ;)

1从技术上讲,这就是真正认真对待始终使用带有控制结构的大括号的人应该如何编写代码。;)

2You can certainly construct counter-examples to this, but it's the general idea of indentation-based syntax.

2您当然可以为此构造反例,但这是基于缩进的语法的一般思想。