Why do we need to use "elif" instead of just another instance of "if" statement? I can understand "else" being necessary.
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.
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 http://www.cprogramming.com ). 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.
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 ;))
Join our real-time social learning platform and learn together with your friends!