Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

#21: Else if

                          << Previous Tutorial           Next Tutorial >>
On this page: elif, comparison operators (==, !=, >, >=, <, <=), comparing strings.

Get Started

Video Summary

  • This initial script was ran three times. This edited version was ran last. The shell outputs here.
  • > is "greater than", and >= is "greater than or equal to". Must use the correct one!
  • The elif keyword is a composite of else and if. Using only else and if, you might have a script looking like the following, where an else statement nests another if statement:
    x = 10
    if x > 9:
        print 'Yay! This works!'
    else:
        if x > 7:
            print 'Wait, what are you doing?'
        else:
            if x > 3:
                print 'Yep, you screwed this up.'
            else:
                print "You just can't get this right, can you?"
    foo.py 
    
    Using elif, you get an equivalent script that is much less cluttered:
    x = 10
    if x > 9:
        print 'Yay! This works!'
    elif x > 7:
        print "Wait, what are you doing?"
    elif x > 3:
        print "Yep, you screwed this up."
    else:
        print "You just can't get this right, can you?"
    foo.py 
    
    (Scripts courtesy of Chris Kovalcik.)
  • In the above scripts, since the initial condition is True, everything under each elif and the else will be ignored, so this program will not be mean to the user, even though it really wants to.
  • The example given in the video is using the elif to determine whether someone can legally do certain things, like drive, smoke, gamble, and drink (in Nebraska).

Learn More

  • A complete list of comparison operators (==, !=, >, >=, <, <=) on this page.
  • The comparison operators can also be applied to strings. With strings, the comparison criterion is the alphabetic order. Note that all uppercase letters come before lowercase letters. If you want to compare the lengths of strings, you must use the len() function.
     
    >>> 'banana' < 'kiwi'
    True 
    >>> 'banana' < 'Kiwi'
    False 
    >>> len('banana') < len('kiwi')
    False 
    
  • As always, Anne Dawson has excellent examples on conditionals. Search for "nested if". She also demonstrates how a nested if statement may be "un-nested" using elif.

Explore