72

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")
11
  • 3
    Check out ruby. It does the same thing. It's not really worth thinking about, IMO. Commented Sep 18, 2010 at 17:23
  • 2
    Check out perl where it's elsif.
    – slebetman
    Commented Sep 18, 2010 at 17:35
  • 3
    Check out bash/sh where it's elif as well.
    – slebetman
    Commented Sep 18, 2010 at 17:36
  • 11
    If you take the time to look at more programming languages, you'll find that this is really not that strange. What you are experiencing is merely your lack of exposure to programming languages.
    – slebetman
    Commented Sep 18, 2010 at 17:38
  • 2
    So, you're basically asking why it's called 'elif' rather than 'elseif' or 'else if', right? Not why there is an 'elif' control structure?
    – JAL
    Commented Sep 18, 2010 at 18:21

8 Answers 8

121

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.

6
  • 56
    @Adam: what about else if where the else and if are in the same line? I think that is what the OP meant. Commented Sep 18, 2010 at 17:02
  • 18
    "else if" isn't always a single keyword. For example, in C#, it's just a nested if similar to how I wrote it out in my first example. It's just that C# doesn't care about whitespace as much as python, so it's valid to write out "else if" on one line. As for why it's called "elif" instead of "elseif", "elsif", or anything else, I have no idea. Languages are different and just because some do things one way, doesn't mean everybody has to follow suit. :)
    – Adam Lear
    Commented Sep 18, 2010 at 18:06
  • 2
    Just to add a bit more context and source: docs.python.org/2/tutorial/controlflow.html
    – Ignacio
    Commented Jul 29, 2013 at 15:03
  • 3
    Never realized that else if in C could be just else and if, I always thought of it as one keyword, but this makes much more sense. C is a small language with no fixed style (that's why Python needs an additional elif) and it would be strange to use just one keyword with a space in it. Thanks haha!
    – Jori
    Commented Jan 4, 2014 at 12:11
  • 2
    This deserves to be the accepted answer imho. My hunch is elif was chosen to keep things nicely aligned (else and elif sharing the same number of characters) and to keep editor column width to a minimum ( the 'else if' keyword taking up plenty more space that the condition could consume) but, again, purely a hunch.
    – rjs
    Commented Mar 10, 2015 at 22:36
87

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.

1
  • 5
    For your first footnote: every C style guide ever written says “always uses braces for control structures” and then has a v1.1 where someone scribbled in “except else if”. Every automated formatted or style checker has a v1.1 where the relatively simple parse tree grew an ugly special case for else if. Every “C but better” language starts it’s design requiring braces, then adds the exception, breaking its one-postcard syntax and trivial parser. (Or they just add an elif/elsif/elsei keyword.)
    – abarnert
    Commented Sep 10, 2018 at 16:41
17

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.

4
  • 19
    the last example is painful to look at. Woe upon whomsoever inflicted this on you're innocent eyes. Commented Sep 18, 2010 at 19:19
  • 20
    I cannot understand how an else if, if it existed in Python, would lead to a brace war. Commented May 20, 2011 at 22:05
  • 5
    @ypercube: answers.google.com/answers/threadview/id/386870.html
    – Lie Ryan
    Commented May 21, 2011 at 6:40
  • @LieRyan You did not answer ypercube's question at all with that link, it is about entirely unrelated topic - it is about the ^H^H^H^H^H expression. Commented Oct 29, 2019 at 12:26
9

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

1
  • 4
    It never occurred to me until this answer that C uses else if while the CPP uses elif, so you often end up with both mixed in a single file. Commented Oct 29, 2013 at 14:52
7

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

-2

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

1
  • 2
    No, elif is the analogue of else if in C, which has precisely equivalent power (even though it's implemented with different parsing rules). You can use else if instead of case even in C. And this certainly has nothing to do with why elif is used in python rather than else if.
    – Ben
    Commented Oct 26, 2012 at 23:02
-3

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

3
  • 24
    I'm not sure how this actually addresses the question of why the Python implementers choose elif rather than else if?
    – Ben
    Commented Oct 27, 2012 at 0:34
  • 14
    elif is not simply a shorthand for else if. else if actually is a syntax error in both python 2 and python 3.
    – JSQuareD
    Commented Jul 13, 2015 at 16:49
  • @JSQuareD That's true, but just as elif was added as a special case, the same could have been done for else if without a colon after else.
    – Neme
    Commented Dec 22, 2016 at 22:33
-8

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.

4
  • 20
    "Python inhertis this from Perl" - Wat?
    – user395760
    Commented Sep 18, 2010 at 17:12
  • 5
    I think they both got it from preceding languages - Python is not at all a descendant of Perl. Commented Sep 18, 2010 at 17:23
  • 4
    s/Perl/Bash/ would have been better since in bash it really is elif. And I believe bash inherited it from sh which is much older than Perl.
    – slebetman
    Commented Sep 18, 2010 at 17:34
  • 7
    'elif' was in Algol 68 (en.wikipedia.org/wiki/ALGOL_68) Commented Sep 18, 2010 at 23:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.