+ 2

Why do I need 'elif'?

I don't understand difference between... if something == 0: print('example 1') if something != 0: print('example 2') ...and... if something == 0: print('example 1') elif something!= 0: print('example 2') Can someone explain when 'elif' is needed?

27th Mar 2022, 10:24 AM
Anton Panasiuk
Anton Panasiuk - avatar
5 Answers
+ 3
Try this example, you will see the difference. The elif won't be tested because the if is true: something = 40 if something > 0: print('example 1') if something < 60: print('example 2') if something > 0: print('example 1') elif something < 60: print('example 2')
27th Mar 2022, 10:33 AM
Paul
Paul - avatar
+ 4
Nice answer Paul. I see elif (else if in other languages) as like having a long piece of paper with a sorted/ordered list on it. Eg:1,2,3,4,5,6,7 The first if check tears off the paper at the condition, eg >=5. Leaves 1,2,3,4 The elif checks another condition but only has the remaining list to check, so if it checked ==6 that number is already torn off. The next elif might test ==3, so the list gets torn but rejoined with 3 missing. Leaving 1,2,4 The next elif might check <4 so it gets value 1,2. Leaving 4 The else catches all remaining possibilities, getting 4. Leaving no values behind. You can use careful order of your if elif checks to tear off the values, or you can use and to check more than 1 condition at a time. The Python BMI project shows how many coders are not yet thinking about tearing off the list. Programmers will tear off values, only needing to check 1 condition each elif.
27th Mar 2022, 8:37 PM
HungryTradie
HungryTradie - avatar
+ 3
Peace Walker something would be either 0 or not 0 and only one time. something can't be 0 or not 0 at the same time So if something is 0 then only if block will work otherwise else block will work in your example no need of 2nd if or elif Here only need if and else So if something == 0: print (x) else: print (y) if something == 0 then something != 0 doesn't make any sense.
27th Mar 2022, 10:43 AM
A͢J
A͢J - avatar
+ 2
Paul , thanks a lot. That was obvious =)
27th Mar 2022, 10:43 AM
Anton Panasiuk
Anton Panasiuk - avatar
+ 2
Both program are correct we can use multiple if statements instead of elif
27th Mar 2022, 4:32 PM
Thangeswaran