Python,为什么要用 elif 关键字?

发布于 2024-09-24 03:57:12 字数 228 浏览 11 评论 0原文

我刚刚开始 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

ゃ懵逼小萝莉 2024-10-01 03:57:12

据我所知,它的存在是为了避免过度缩进。你可以写,

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

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

写得更好。


感谢 igndocs 参考:

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

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 ign for the docs reference:

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

过气美图社 2024-10-01 03:57:12

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

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

这意味着,一旦您实现了 ifelseelse if 就会自然而然地脱离该语言的语法,而无需任何操作。进一步加大落实力度。要了解原因,请看一下:

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

这看起来像一个 if,附加了一个 else if 和一个 else,每个都应用于一个复合陈述。但事实上并非如此。这实际上是两个独立的 if 语句,每个语句都有一个 else 情况;第二个 if 语句位于第一个 if 语句的 else 主体内。

else if { ... } 实际上被解析为应用于下一个语句的 else,这是一个 if 语句(应用于复合语句{ else_if_body(); }。然后最后的 else 绑定到前面的 if,这是第二个

。更符合它的解析方式1

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

但事实证明,如果该语言确实直接实现 else if 作为 if 语句,它的行为与第一个语句的 else 内的第二个独立 if 语句完全相同,因此无需费心实现! else if 完全可用;一旦实现了 ifelse,语言实现者就可以免费使用这种语法风格。

的语法不允许使用

C 风格语法的程序员可以用 else if 来思考,即使该语言只有 。 if 恰好是零或一个 else,但这仅仅是因为他们可以编写像我的第一个示例一样的代码,其格式对于人类读者来说看起来与对于普通读者来说不同。编译器。

Python,OTOH,使用缩进来指示块结构,这迫使块结构对于人类读者来说看起来与对于解释器2来说是一样的。一旦您掌握了 Python 风格语法中的 ifelse,程序员仍然可以编写与 else-if 行为相同的代码,方法是:将第二个 if 语句放入第一个 else 语句中。但结果看起来像这样:

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

这看起来很丑陋,而且一旦你得到超过 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 and else, 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:

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

This looks like an if with an else if and an else attached, each applied to a compound statement. But in fact it's not. This is actually two separate if statements, each with exactly one else case; the second if statement is inside the body of the else of the first if statement.

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

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

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 if as a first-class option for if statements, it would behave exactly the same as the second independent if statement inside the else of the first! So there's no need to bother implementing else if at all; language implementers get else if for free with this style of syntax, once they've implemented if and else.

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 has if with 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.

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 and else in Python-style syntax, programmers could still write code that behaves identically to an else-if, by putting a second if statement inside the else of a first. But that comes out looking like this:

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 thinking in 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 else except the last contains exactly one if 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 choose elif? 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.

微暖i 2024-10-01 03:57:12

为了避免大括号^H^H^H^H^Helse,如果发生战争。

在有 else if 的 C/C++ 中,您可以用多种不同的风格构建代码:

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


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

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

// and so on

通过使用 elif 来代替,这样的战争永远不会发生,因为只有编写elif的一种方法。此外,elifelse 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:

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


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

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

// and so on

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

梦萦几度 2024-10-01 03:57:12

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

That's just the way it is. Javascript uses else if, php uses elseif, perl uses 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

青春如此纠结 2024-10-01 03:57:12

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

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

静若繁花 2024-10-01 03:57:12

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

例如在 C 语言中,您

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

用 Python 编写,

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

如您所见, 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

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

in Python you write

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

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

萌面超妹 2024-10-01 03:57:12

最有可能的是语法糖。就像 Visual Basic 的 Wend 一样。

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

番薯 2024-10-01 03:57:12

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 have else: 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 the not in operator.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文