Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

What is the point of the elif statment?

  1. Sep 27, 2015 #1
    What's the point of the elif statment? Why not just keep the if and else statements and leave it at that? Can't the if statement be replaced with just if? Thanks.
     
  2. jcsd
  3. Sep 27, 2015 #2

    Mark44

    Staff: Mentor

    It's short for else if. A simple if ... else statement is used to choose one of two possible alternatives. If you have to choose among three or more alternatives you want a control structure that looks like this (using C rather than python, though):
    Code (C):
    if (val == opt1)
    {
       // Option for opt1
    }
    else if (val == opt2)
    {
       // Option for opt2
    }
    else
    {
       // Otherwise do this
    }
    If my code has to choose among more possibilities, I can add more else if clauses (or elif in python).
     
  4. Sep 27, 2015 #3

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Compiled languages tend not to have an elif statement, or something similar. They instead use something along the lines of

    Code (C):
    if (condition) {
        do_this;
    } else if (other_condition) {
        do that;
    The elif statement, or something similar, is much more common in scripting languages. With python, it's almost essential because of the indentation rules and PEP8, the python indentation standard. Consider the following:
    Code (Python):

    class Foo :
        def fun (self, val) :
            if val == 0 :
                self.handle_zero ()
            else :
                if val == 1 :
                    self.handle_one ()
                else :
                    if val == 2 :
                        self.handle_two ()
                    else :
                        # Lines are supposed to be at most 79 characters long in python.
                        # Do you see how quickly I'm running out of space?
                        # There are lots of enums with 16 or more members.
                        pass
    Many other languages have a switch statement. Python doesn't. You either need to use a dictionary, an incredibly ugly stair-stepped if ... else if ... else if ... sequence of tatements, or you could use elif.
     
  5. Sep 27, 2015 #4
    See 4.1 in https://docs.python.org/3/tutorial/controlflow.html for justification.

    This doesn't make sense. I'm guessing you mean "Can't the elif statement be replaced with just if?" If so, the following are not logically equivalent:

    Code (Text):

    if A:
      a()
    elif B:
      b()
    else:
      c()

    if A:
      a()
    if B:
      b()
    else:
      c()

     
    In the latter block, the first test is independent of the second.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook