My
goal here is to create a simple example for using Exception Handling and
Pickling in Python. For the Exception handling I created a simple program that
asks for a dog’s age in human years and returns the dog’s age in “dog” years.
The user needs to enter a whole number that is positive. If the user fails to
enter a positive whole number then the error exceptions catch the mistake and
print an error message. Afterwards you will see a simple example of the
Pickling technique which stores a dictionary, then loads the data and finally
prints the result to display the binary information as a normal dictionary
string once again.
Let’s
begin with the Exception handling. There are two error exceptions, the first
one recognizes if the user has entered a negative value with the help of a
calculation which generates a “ZeroDivisionError” if the value entered is negative.
Its simpler than it looks; the denominator (bottom of the division equation) is
the sum of the original value plus its absolute value. If the value is
negative, then the absolute value is positive. When you add the absolute value
with the original negative number it will always equal zero. As a result, the
division is 1 divided by 0, which will generate an error. This is why the
printed message for “ZeroDivisionError” is letting the user know the value they
enter must be positive. On the other hand, if the value is positive, then the
denominator will be a non-zero number, which means the division is valid.
The
second exception handles the user entering the wrong type specified. In this
case, the type specified was integer, so if the user has not entered an integer
then the error message lets the user know that they must enter a whole number. Note
that for the “ValueError” exception to work, the integer assignment needs to
happen within the “try” section of the code. Otherwise if the value is assigned
as integer prior to the “try-except” code, then the exception handling for
non-integer values occurs prior to the “try-except” code being executed. And as
a result, you will not get the print message to output which you created to
handle the non-integer error.
# -- Data --#
# v1 = Age of dog (in years)
# intDogYears = Age of dog in dog years
# ( human years multiplied by 7)
# checkPositive = equation that returns a "
# Zero Division Error" if the user inputs a negative age for the dog. # -- Input/Output --# # user inputs dog's age in "human" years. # program returns the dog's age in "dog" years. # -- Processing --# # Step 1 # When the user inputs the dog's age in "human" years, it calculate the dog's age in "dog" years. # Exception1 # if the age entered is zero or negative the user receives an error message. # Exception2 # if the age entered is not a whole number the user receives an error message. # ------------------------------- # -- Input --# v1 = input('How old is your dog (in "human" years)?: ') # -- Processing --# # Step 1: # When the user inputs the dog's age in "human" years, # it calculate the dog's age in "dog" years. try: v1 = int(v1) intDogYears = v1*7 checkPositive = 1 / (v1 + abs(v1)) print('Your dog is ',intDogYears,' years old in "dog years".') if v1>20: print('WOW!!! Your dog must be very wise, having lived all those years!!!') # Exception1 # if the age entered is zero or negative, # the user receives an error message. except ZeroDivisionError: print("ERROR: Value must be greater than Zero.") # Exception2 # if the age entered is not a whole number, # the user receives an error message. except ValueError: print("ERROR: Input must be a whole number!")
Now let’s review the Pickling Handling. To enable Pickling, you need to first tell the program to “import” the “pickle” technique by simply writing the code “import pickle”. Then I setup my code to collect a list of rows into a dictionary, which I will then load using the pickling technique.
# Initiate the Pickle programming
import pickle
# Assign a dictionary variable and prepare
# the index that will be used in the while loop
database = []
intId = 0
# while loop for the pickling example:
# while loop while intID is less than 4
# (intID serves as a counter to break the loop).
# lstCustomer will capture the list row
# and will be appended to the "database" dictionary
while (intId < 4):
intId = intId + 1
strName = str(input("Enter a Name: "))
lstCustomer = {intId, strName}
database.append(lstCustomer)
print(database)
import pickle
# Assign a dictionary variable and prepare
# the index that will be used in the while loop
database = []
intId = 0
# while loop for the pickling example:
# while loop while intID is less than 4
# (intID serves as a counter to break the loop).
# lstCustomer will capture the list row
# and will be appended to the "database" dictionary
while (intId < 4):
intId = intId + 1
strName = str(input("Enter a Name: "))
lstCustomer = {intId, strName}
database.append(lstCustomer)
print(database)
Now
we use the pickle code. First open the file and tell the program you want to
recognize the data as binary, so remember to use the “ab” mode for binary. Next
store the database dictionary into the file with “pickle.dump()”.
# Now we store the data with the pickle.dump method
# "ab" code will setup the file to receive binary data
objFile = open("C:\\_PythonClass\\Customers.dat", "ab")
pickle.dump(database, objFile)
objFile.close()
# "ab" code will setup the file to receive binary data
objFile = open("C:\\_PythonClass\\Customers.dat", "ab")
pickle.dump(database, objFile)
objFile.close()
Finally, read the data with the “pickle.load()” code. At first I didn’t understand the instructions that mentioned that this command would only load one row of data, but now I see when I re-run the code that the second set of information that was appended to the dictionary was added to the “.dat” file, but it was not read by the “pickle.load()” command. This is useful to know so if I need to append more information in the future it would be best to read the information into the python code into a new dictionary, then add new information and finally overwrite the original “.dat” file completely with the new dictionary. In any case, this simple example is a good start to understand how to store and read information from a binary file.
# And, we read the data back with the same pickle.load method
# "rb" allows the binary file to be read as binary script
objFile = open("C:\\_PythonClass\\Customers.dat", "rb")
objFileData = pickle.load(objFile) #Note that load() only loads one row of data.
print('-----------------------------------------------------')
print('OUTPUT of the binary file loaded with the Pickle technique')
print(objFileData)
# "rb" allows the binary file to be read as binary script
objFile = open("C:\\_PythonClass\\Customers.dat", "rb")
objFileData = pickle.load(objFile) #Note that load() only loads one row of data.
print('-----------------------------------------------------')
print('OUTPUT of the binary file loaded with the Pickle technique')
print(objFileData)
Comments
Post a Comment