When to use elif? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

When to use elif?

I know what 'elif' does but I rarely feel it is necessary, since often a second 'if' in a row anyway happens only if the first 'if' is False (a bit like in c++s 'switch'). What do you think, when should 'elif' be used, only when really necessary or even in cases where 'if' would suffice (for clarity reasons or whatever)?

27th Aug 2018, 4:14 PM
HonFu
HonFu - avatar
6 Answers
+ 1
Got ya - the main case would be where your if returns something, which would stop the execution flow anyway, so the elif is redundant in this case. Personally, I prefer to keep it because it keeps everything at the same indentation level, and I think it's a little tidier in Java (which is the main language I use) In my first response, I meant to say that I find elif is required much more often than the situation you described.
27th Aug 2018, 4:41 PM
Dan Walker
Dan Walker - avatar
+ 1
I think in this case, I would still prefer an elif, because the subsequent if conditions will still be checked. If any of these Boolean checks were expensive then it could impact the performance of the program (unlikely, but is slightly wasteful for the sake of two characters :p)
27th Aug 2018, 5:30 PM
Dan Walker
Dan Walker - avatar
0
Your first paragraph is false. This code: if statement1: // do this if statement2: // do another thing. if both statements are true, both blocks will execute, which may not be the intended behavior. An elif statement is required if you want to do one of these things only
27th Aug 2018, 4:24 PM
Dan Walker
Dan Walker - avatar
0
That was not really my question, Dan. In cases where I have to, I obviously use elif. I was wondering if people use it even when it's not strictly necessary, for style issues or whatever.
27th Aug 2018, 4:28 PM
HonFu
HonFu - avatar
0
Yeah, I mean cases like that where you break or return and the other conditions can't happen anyway. But also for example if you ask for a choice of several options. if choice == '1': do this and that. if choice == '2':... Since the choice was not 1, elif is not really needed; but logically it still is an either or, right? At least for humans...
27th Aug 2018, 4:48 PM
HonFu
HonFu - avatar
0
Ah, okay, so there's an efficiency issue at work here too: Don't check what doesn't need to be checked ... good point!
27th Aug 2018, 5:50 PM
HonFu
HonFu - avatar