Python, why elif keyword? [closed]

2019-01-22 05:45发布

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")

8条回答
唯我独甜
2楼-- · 2019-01-22 06:13

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.

查看更多
闹够了就滚
3楼-- · 2019-01-22 06:15

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.

查看更多
登录 后发表回答