Pattern Matching: Introduction

Say you're working in a recycling facility and want to write a program that will sort the aluminum, paper, and plastic recyclables. This would be easy enough to write using if statements:

def sortItems(recyclable):

    """sort the items based on material"""
    if recyclable is aluminum:
        """execute code to put recyclable into the aluminum bin"""
    elif recyclable is paper:
        """execute code to put recyclable into the paper bin"""
    elif recyclable is plastic:
        """execute code to put recyclable into the plastic bin"""
    else:
        raise TypeError("item not recyclable")

...But there's an easier and cleaner way to do it.


Next
Previous