Skip to main content

Assignment07: Exception Handling and Pickling

For Assignment07, we were tasked with researching online and then writing two simple Python code examples that illustrate:
  1. how to use Python's exception handling features
  2. how to use Python's "pickling" features

After watching Randal's lecture videos and reading Chapter 7 from Michael Dawson's Python Programming for the Absolute Beginner, Third Edition, I ran a few Google searches on the two topics to find tutorials, hopefully for beginners!

For exception handling, I read (or tried to read, at least!) the following web pages:

For using the pickle module, I read the following web pages:

Ultimately, I found that these different perspectives complemented what Randal taught us and what was in our class textbook, sometimes going into more detail than I probably needed for the purposes of this introductory class and assignment. So, I modeled my code examples more in the style of Randal's labs or the Dawson text.

Without further ado, here is the first of my two code examples:

# ------------------------------------------------- #
# Title: Exception Handling (Assignment 07)
# Dev: GBiller
# Date: May 14, 2018
# ChangeLog: (Who, When, What)
#
# ------------------------------------------------- #


# Create a simple example of how you would use Python Exception Handling.

# Define functions to add, subtract, multiply, and divide two numbers
def askForANumber(strMessage):
    """Asks for a number from the user using strMessage as the prompt"""
    try:
        flt1 = float(input(strMessage))
        return flt1
    except ValueError as e: # Exception when non-numeric string is entered
        print("\nError! Please enter a number.\n")
        return None
    except Exception as e: # Any other exception
        print("Error!", e.__class__)

def addTwoNumbers(x, y):
    return x + y

def subtractTwoNumbers(x, y):
    return x - y

def multiplyTwoNumbers(x, y):
    return x * y

def divideTwoNumbers(x, y):
    try:
        return x / y
    except ZeroDivisionError as e:
        return "Undefined"
    except Exception as e:
        print("Error!", e.__class__)

# Get two numbers from the userwhile True:
    num1 = askForANumber("Enter first number: ")
    if num1 is not None: break

while True:
    num2 = askForANumber("Enter second number: ")
    if num2 is not None: break

# Print results to the consoleprint("\n" + str(num1) + " + " + str(num2) + " = " + str(addTwoNumbers(num1, num2)))
print(str(num1) + " - " + str(num2) + " = " + str(subtractTwoNumbers(num1, num2)))
print(str(num1) + " * " + str(num2) + " = " + str(multiplyTwoNumbers(num1, num2)))
print(str(num1) + " / " + str(num2) + " = " + str(divideTwoNumbers(num1, num2)))



And, finally, here is the second of my two code examples:

# ------------------------------------------------- #
# Title: Pickling (Assignment 07)
# Dev: GBiller
# Date: May 14, 2018
# ChangeLog: (Who, When, What)
#
# ------------------------------------------------- #

# Create a simple example of how you would use Python Pickling.

import pickle

# create 3 dictionaries of customer infodicCust1 = {"ID": "1", "Name": "Joe Schmoe", "Email": "joeschmoe@gmail.com"}
dicCust2 = {"ID": "2", "Name": "Jill Hill", "Email": "jillhill@yahoo.com"}
dicCust3 = {"ID": "3", "Name": "Barry White", "Email": "bwhite@live.com"}

# create a list of the dictionarieslstCustomers = [dicCust1, dicCust2, dicCust3]

# open binary file for writingobjFile = open("pickled customers.dat", "wb")
pickle.dump(lstCustomers, objFile)
print("\nSaving customers to binary file... Saved!")
objFile.close()

input("\nPress enter to continue...")

# open binary file for reading, then loop through list of dictionaries
# and print out the customer info

print("\nUnpickling customers from binary file:")
objFile = open("pickled customers.dat", "rb")
lstCustomers = pickle.load(objFile)
for dicRow in lstCustomers:
print("\t" + dicRow["ID"] + ", " + dicRow["Name"] + ", " + dicRow["Email"])
objFile.close()

Comments