Hacking Secret Ciphers with Python

(Ann) #1
Chapter 12 – Detecting English Programmatically 179

it is not an English word. We are relying on the dictionary file to be accurate and complete in
order for the detectEnglish module to work correctly.


“Divide by Zero” Errors


detectEnglish.py


  1. return float(matches) / len(possibleWords)


Returning a float value between 0.0 and 1.0 is a simple matter of dividing the number of
recognized words by the total number of words.


However, whenever we divide numbers using the / operator in Python, we should be careful not
to cause a “divide-by-zero” error. In mathematics, dividing by zero has no meaning. If we try to
get Python to do it, it will result in an error. Try typing the following into the interactive shell:





42 / 0
Traceback (most recent call last):
File "<pyshell# 0 >", line 1, in
42 / 0
ZeroDivisionError: int division or modulo by zero





But a divide by zero can’t possibly happen on line 36. The only way it could is if
len(possibleWords) evaluated to 0. And the only way that would be possible is if
possibleWords were the empty list. However, our code on lines 29 and 30 specifically checks
for this case and returns 0.0. So if possibleWords had been set to the empty list, the
program execution would have never gotten past line 30 and line 36 would not cause a “divide-
by-zero” error.


The float(), int(), and str() Functions and Integer Division


detectEnglish.py


  1. return float(matches) / len(possibleWords)


The value stored in matches is an integer. However, we pass this integer to the float()
function which returns a float version of that number. Try typing the following into the interactive
shell:





float(42)
42.0




Free download pdf