For e.g..
According to some experts,
The conditions here are mutually exclusive:
if(n>0):
print "Number is Positive"
if(n<0):
print "Number is Negative"
if(n==0):
print "Number is ZERO"
It would be better to rewrite with elif and else:
if n > 0:
print "Number is Positive"
elif n < 0:
print "Number is Negative"
else:
print "Number is ZERO"
So I just want to ask the question that , Is there any difference between ' if ' and ' elif ' . I know the basic difference between ' if ' and ' elif '. But I just want to know , Why some novice programmers prefer ' elif ' over ' if '?
Conditional Statements Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
While the if-else if statement only executes the latter if statement when the first if statement is false, multiple if statements are guaranteed to execute all of them.
The first form if-if-if test all conditions, whereas the second if-elif-else tests only as many as needed: if it finds one condition that is True, it stops and doesn't evaluate the rest. In other words: if-elif-else is used when the conditions are mutually exclusive. Hope this answers your question!!!
The first form if-if-if
tests all conditions, whereas the second if-elif-else
tests only as many as needed: if it finds one condition that is True
, it stops and doesn't evaluate the rest. In other words: if-elif-else
is used when the conditions are mutually exclusive.
Let's write an example. if you want to determine the greatest value between three numbers, we could test to see if one is greater or equal than the others until we find the maximum value - but once that value is found, there is no need to test the others:
greatest = None
if a >= b and a >= c:
greatest = a
elif b >= a and b >= c:
greatest = b
else:
greatest = c
print greatest
Alternatively, we could assume one initial value to be the greatest, and test each of the other values in turn to see if the assumption holds true, updating the assumed value as needed:
greatest = None
if a > greatest:
greatest = a
if b > greatest:
greatest = b
if c > greatest:
greatest = c
print greatest
As you can see, both if-if-if
and if-elif-else
are useful, depending on what you need to do. In particular, the second of my examples is more useful, because it'd be easy to put the conditional inside a loop - so it doesn't matter how many numbers we have, whereas in the first example we'd need to write many conditions by hand for each additional number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With