• anonymous
Why do we need to use "elif" instead of just another instance of "if" statement? I can understand "else" being necessary.
MIT 6.00 Intro Computer Science (OCW)
  • Stacey Warren - Expert
Hey! We 've verified this expert answer for you, click below to unlock the details :)
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
  • katieb
I got my questions answered at in under 10 minutes. Go to now for free help!
  • anonymous
Basically, elif is a short hand for else if (different languages use a different keyword. I've seen elif, elsif and else if). The advantage of using a else if is that your indentation does not suffer. Take for example a simple test: if n == 1: # do something elif n == 2: # Do something else elif n == 3: # Do a third thing else # Do a final thing Without the elif this would have to become: if n == 1: # Do something else if n == 2: # Do something else else: if n == 3: # Do a third thing else: # Do a final thing Imagine a larger series of if ... else if statements. It would be easy to make a mistake with indentation there, while the elif keeps things nice and readable.
  • rsmith6559
If you have several possibilities, elif allows your condition to only have to be evaluated once and the result chosen from the various if/elif/else. A series of if statements require the condition to be evaluated every time, which can be expensive. If this is Python, Python is unusual in that it doesn't have a switch statement ( you may want to check a site like ). They use the if/elif/else instead, ostensibly to be easier to read. I'll bet that down in the interpreter, it's doing a switch statement.
  • anonymous
Thank you for your replies. @slotema, I had suspected that but wasn't sure why not just repeat the "if" statement until an "else" is needed, I see we can repeat an elif instead. @rsmith on a side note, you remind me how much I love The Cure ;) Yes this is python, I should have mentioned that. Thanks again. Really enjoying the lectures (I was previously learning ruby the hard way ;))

Looking for something else?

Not the answer you are looking for? Search for more explanations.