Python,为什么要用 elif 关键字?
我刚刚开始 Python 编程,我想知道 elif 关键字。
我之前使用过的其他编程语言都使用 else if
。有谁知道为什么 Python 开发人员添加了额外的 elif 关键字吗?
为什么不:
if a:
print("a")
else if b:
print("b")
else:
print("c")
I just started Python programming, and I'm wondering about the elif
keyword.
Other programming languages I've used before use else if
. Does anyone have an idea why the Python developers added the additional elif
keyword?
Why not:
if a:
print("a")
else if b:
print("b")
else:
print("c")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
据我所知,它的存在是为了避免过度缩进。你可以写,
但
写得更好。
感谢 ign 的 docs 参考:
Far as I know, it's there to avoid excessive indentation. You could write
but
is just so much nicer.
Thanks to ign for the docs reference:
具有类似 C 语法的语言可以免费获得
else if
,而无需实现它。原因是,在该语法控制结构中,仅对下一条语句进行操作,如果需要,下一条语句可以是用大括号括起来的复合语句(例如
{x += 1; y += 1 }
)。这意味着,一旦您实现了
if
和else
,else if
就会自然而然地脱离该语言的语法,而无需任何操作。进一步加大落实力度。要了解原因,请看一下:这看起来像一个
if
,附加了一个else if
和一个else
,每个都应用于一个复合陈述。但事实上并非如此。这实际上是两个独立的if
语句,每个语句都有一个else
情况;第二个if
语句位于第一个if
语句的else
主体内。else if { ... }
实际上被解析为应用于下一个语句的else
,这是一个if
语句(应用于复合语句{ else_if_body(); }
。然后最后的else
绑定到前面的if
,这是第二个。更符合它的解析方式1:
但事实证明,如果该语言确实直接实现
else if
作为if
语句,它的行为与第一个语句的else
内的第二个独立if
语句完全相同,因此无需费心实现!else if
完全可用;一旦实现了if
和else,语言实现者就可以免费使用这种语法风格。
的语法不允许使用
C 风格语法的程序员可以用
else if
来思考,即使该语言只有。 if
恰好是零或一个else
,但这仅仅是因为他们可以编写像我的第一个示例一样的代码,其格式对于人类读者来说看起来与对于普通读者来说不同。编译器。Python,OTOH,使用缩进来指示块结构,这迫使块结构对于人类读者来说看起来与对于解释器2来说是一样的。一旦您掌握了 Python 风格语法中的
if
和else
,程序员仍然可以编写与 else-if 行为相同的代码,方法是:将第二个if
语句放入第一个else
语句中。但结果看起来像这样:这看起来很丑陋,而且一旦你得到超过 1 或 2 个 else-if,就比 else-if 链思考起来要复杂得多。因此,值得添加显式语言功能,以恢复根据 else-if 进行思考的能力。尽管它在技术上使语言变得更加复杂,但它实际上使语言的思考变得更简单,因此它的复杂性很好;如果在
else
内手动构建嵌套的if
链,读者必须手动读取所有代码并验证除最后一个之外的所有else
仅包含一个if
语句,仅包含一个if
语句,以便得出结论,整个序列相当于按顺序检查的线性条件链,并在第一个成功的检查中执行一些代码。那么。我们已经看到,具有类似 C 语法的语言也可能使用
else if
,因为它们是免费的。这就是它存在的原因。具有类似 Python 语法的语言必须显式执行某些操作才能获得可用作 else-if 的构造。他们为什么选择elif
?这是任意的;你必须真正询问做出决定的人。然而,Python 并没有发明 elif,早在 Python 出现之前,它就已经在其他语言中出现了。因此,我猜测,当他们必须实现显式的 else-if 结构时,他们只是选择了程序员已经熟悉的结构。
1 从技术上讲,这就是那些真正认真地始终使用带控制结构的大括号的人应该如何编写代码。 ;)
2 您当然可以构造反例,但这是基于缩进的语法的一般思想。
Languages with C-like syntax get
else if
for free without having to implement it at all.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 }
).This means that once you've implemented
if
andelse
,else if
just falls out of the grammar of the language naturally for free, with no further implementation effort. To see why, have a look at this:This looks like an
if
with anelse if
and anelse
attached, each applied to a compound statement. But in fact it's not. This is actually two separateif
statements, each with exactly oneelse
case; the secondif
statement is inside the body of theelse
of the firstif
statement.else if { ... }
is really parsed aselse
applied to the next statement, which is anif
statement (applied to the compound statement{ else_if_body(); }
. Then the finalelse
binds to the immediately precedingif
, which is the second one.Here's the same thing written more in line with how it's parsed1:
But it turns out that if the language did directly implement
else if
as a first-class option forif
statements, it would behave exactly the same as the second independentif
statement inside theelse
of the first! So there's no need to bother implementingelse if
at all; language implementers getelse if
for free with this style of syntax, once they've implementedif
andelse
.Python's syntax doesn't allow this freebie.
Programmers of C-style syntax can think in terms of
else if
even though the language only hasif
with exactly zero-or-oneelse
, 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.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
if
andelse
in Python-style syntax, programmers could still write code that behaves identically to an else-if, by putting a secondif
statement inside theelse
of a first. But that comes out looking like this: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 thinking in terms of the language simpler, so it's good complexity; with a manually constructed chain of nested
if
s insideelse
s the reader has to manually read all the code and verify that everyelse
except the last contains exactly oneif
statement 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.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 chooseelif
? It's arbitrary; you'd have to actually ask the people who made the decision.However Python didn't invent
elif
, it was around in other languages long before Python existed. So I would guess that when they had to implement an explicit else-if construct they simply picked one that programmers were already familiar with.1 Technically, this is how people who are REALLY serious about always using braces with control structures should write their code. ;)
2 You can certainly construct counter-examples to this, but it's the general idea of indentation-based syntax.
为了避免大括号^H^H^H^H^Helse,如果发生战争。
在有
else if
的 C/C++ 中,您可以用多种不同的风格构建代码:通过使用
elif
来代替,这样的战争永远不会发生,因为只有编写elif
的一种方法。此外,elif
比else if
短得多。To avoid brace^H^H^H^H^Helse if war.
In C/C++ where you have an
else if
, you can structure your code in many different styles:by having an
elif
instead, such war would never happen since there is only one way to write anelif
. Also,elif
is much shorter thanelse if
.事情就是这样。 Javascript 使用
else if
,php 使用elseif
,perl 使用elsif
,C 预处理器和 python 使用elif
。他们都没有错,他们只是选择稍微不同的语法来完成同样的事情。 :DThat's just the way it is. Javascript uses
else if
, php useselseif
, perl useselsif
, the C preprocessor and python useelif
. None of them are wrong, they just choose slightly different syntax to do the same thing. :D我发现它们有助于区分“else-if”和“final else”。
I find them helpful to help differentiate the "else-if"s from the "final else".
elif 是其他语言中 switch 的某种替代品,但功能更强大,
例如在 C 语言中,您
用 Python 编写,
如您所见, elif 更强大,因为您可以放置比 switch 更复杂的语句,加上避免嵌套
if/else
语句elif is some sort of replacement for switch in other languages but with more power
for example in C you write
in Python you write
As you see
elif
is more powerful since you can put more complex statements than in a switch, plus avoid nestingif/else
statements最有可能的是语法糖。就像 Visual Basic 的
Wend
一样。Most likely it's syntactic sugar. Like the
Wend
of Visual Basic.Python 从 Perl 继承了这一点,在 Perl 中称为
elsif
。在 Python 的情况下,
else if
作为两个独立的结构(就像在类 C 语言中一样)会非常难看,因为您必须使用带有两个缩进的else: if:
水平。将两个关键字一起使用特殊大小写是否会更好是有争议的(因此将
else if
制作为单个构造,如not in
运算符。PL/SQL 也有
elsif
,C 预处理器将其拼写为elif
。Python inherits this from Perl, where it's called
elsif
.In Python's case,
else if
as two separate constructs like it is in C-like languages would be quite ugly as you'd have to haveelse: if:
with two indenting levels.It's arguable whether special-casing the two keywords together would be better (so making
else if
a single construct, like thenot in
operator.PL/SQL also has
elsif
, and the C preprocessor has it spelledelif
.