Difference between multiple if's and elif's?

Multiple if's means your code would go and check all the if conditions, where as in case of elif, if one if condition satisfies it would not check other conditions..


An other easy way to see the difference between the use of if and elif is this example here:

def analyzeAge( age ):
   if age < 21:
       print "You are a child"
   if age >= 21: #Greater than or equal to
       print "You are an adult"
   else:   #Handle all cases where 'age' is negative 
       print "The age must be a positive integer!"

analyzeAge( 18 )  #Calling the function
>You are a child
>The age must be a positive integer!

Here you can see that when 18 is used as input the answer is (surprisingly) 2 sentences. That is wrong. It should only be the first sentence.

That is because BOTH if statements are being evaluated. The computer sees them as two separate statements:

  • The first one is true for 18 and so "You are a child" is printed.
  • The second if statement is false and therefore the else part is executed printing "The age must be a positive integer".

The elif fixes this and makes the two if statements 'stick together' as one:

def analyzeAge( age ):
   if age < 21:
       print "You are a child"
   elif age > 21:
       print "You are an adult"
   else:   #Handle all cases where 'age' is negative 
       print "The age must be a positive integer!"

analyzeAge( 18 )  #Calling the function
>You are a child

Edit: corrected spelling


def multipleif(text):
    if text == 'sometext':
        print(text)
    if text == 'nottext':
        print("notanytext")

def eliftest(text):
    if text == 'sometext':
        print(text)
    elif text == 'nottext':
        print("notanytext")

text = "sometext"

timeit multipleif(text)
100000 loops, best of 3: 5.22 us per loop

timeit eliftest(text)
100000 loops, best of 3: 5.13 us per loop

You can see that elif is slightly faster. This would be more apparent if there were more ifs and more elifs.