Skip to content Skip to sidebar Skip to footer

What's The Main Difference Between 'if' And 'else If'?

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

Solution 1:

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 = Noneif 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=Noneifa>greatest:greatest=aifb>greatest:greatest=bifc>greatest:greatest=cprintgreatest

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.

Solution 2:

You can chain if with elif and finish with an else if none of the conditions in the chain were met. When checking through the statements, it will find the first matching one and execute the instructions within that block, then break from the if/elif/else block

n = 6
if n % 2 == 0:
  print('divisible by 2')
elif n % 3 == 0:
  print('divisible by 3')
else:
  print('not divisible by two or three')

this would print

divisible by2

However, say you replace that elif above with an if and remove the else clause...

divisible by2
divisible by3

the elif chains the statements and chooses the first appropriate one.

Post a Comment for "What's The Main Difference Between 'if' And 'else If'?"