Python Python Basics Types and Branching If, Else and Elif

aditya verma
aditya verma
1,069 Points

Difference between elif and if

In the example, there are three possible names, couldnt we have written 'if' statement for Craig and Maximilian and else for the family member.

In short whats the difference between using elif versus if in the second codition of maximiliane?

1 Answer

Steven Parker
Steven Parker
200,784 Points

An "elif" condition is only tested if the previous "if" test was false. When you use another "if" instead of "elif", then the second condition will always be tested, no matter what the result of the first one was.

Proper use of "elif" will usually make the program more efficient, plus it allows you to use logical progressions that would not work with a plain "if". For example:

if value > 60:
    print "Large"
elif value > 30:     # a plain "if" would not work here
    print "Medium"
    print "Small"

Substituting a plain "if" for the "elif" would cause a value over 60 to print out both "Large" and "Medium".