A community for students.

Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing


  • 4 years ago

Why do we need to use "elif" instead of just another instance of "if" statement? I can understand "else" being necessary.

  • This Question is Closed
  1. anonymous
    • 4 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    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.

  2. rsmith6559
    • 4 years ago
    Best Response
    You've already chosen the best response.
    Medals 2

    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.

  3. anonymous
    • 4 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

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

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

    • Attachments:

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy

Your question is ready. Sign up for free to start getting answers.

spraguer (Moderator)
5 → View Detailed Profile

is replying to Can someone tell me what button the professor is hitting...


  • Teamwork 19 Teammate
  • Problem Solving 19 Hero
  • You have blocked this person.
  • ✔ You're a fan Checking fan status...

Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy.

This is the testimonial you wrote.
You haven't written a testimonial for Owlfred.