Go to: Na-Rae Han's home page  

Python 3 Notes

        [ HOME | LING 1330/2330 ]

Tutorial 18: Else if

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

Video Tutorial


Python 3 Changes

print(x,y) instead of print x, y

input() instead of raw_input()

Video Summary

  • > 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