Pass—Python

Python has a special pass keyword to do nothing. Here’s a code example

countdown = 15
while countdown > 0:
    if countdown > 10:
        pass # Don't do anything yet
    else:
        print('T - ', str(countdown))
    countdown -= 1
else:
    print ('We have liftoff!')

This code simulates a countdown, but we don’t actually want to print anything to the console until we get to 10. In this case, we set up an if condition that checks if countdown is greater than 10. If countdown is greater than 10, we use pass to do nothing.

In the real world, I tend to use pass when I am developing. Here is an example

def onNew():
    #TODO: Handle new file here
    pass

def onSave():
    #TODO: Handle saving a file here
    pass

def onOpen():
    #TODO: Handle opening a file here
    pass

def onError():
    #TODO: Handle user input errors here
    pass

repeat = True
while repeat:
    print('1) New...')
    print('2) Open...')
    print('3) Save...')
    print('4) Quit...')

    choice = input('Enter an option => ')
    if choice == 1:
        onNew()
    elif choice == 2:
        onOpen()
    elif choice == 3:
        onSave()
    elif choice == 4:
        repeat = False
    else:
        onError()

In this programming example, I’m in the process of developing a menu drive user interface. You can see the menu printed out in the while loop. The user is asked for a choice and then if/elif statements are used to respond to their choice. In each choice except 4, we are using function to handle the user’s choice. This keeps the user reponse code seperate from the user menu code (concept know as seperations of concerns).

Above the menu loop there are four functions: onNew(), onOpen(), onSave(), and onError(). Every single one of these functions has the pass keyword. Eventually the pass statements will get replaced with actual code to handle each event, but for now, I only want to test the menu code. Using pass in this fashion lets me run the program and make sure the menu is working properly before I continue developing the rest of the program.

Advertisements

1 thought on “Pass—Python”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s