I have altered a program to allow for rounding to 2dps but despite having successfully eliminating it prior "ZeroDivisionError: float division" has returned. What alterations do I need to make to avoid the error using the most elegant method?
Was:
for line in data:
split=line.split()
ptot=0
ntot=0
for pchar in "HKR":
pchartotal=split[1].count(pchar)
ptot+=pchartotal
for nchar in "DE":
nchartotal=split[1].count(nchar)
ntot+=nchartotal
try:
print float(ptot)/float(ntot)
except ZeroDivisionError:
print ptot
Is:
for line in data:
split=line.split()
ptot=0
ntot=0
for pchar in "HKR":
pchartotal=split[1].count(pchar)
ptot+=pchartotal
for nchar in "DE":
nchartotal=split[1].count(nchar)
ntot+=nchartotal
ratio=float(ptot)/float(ntot)
try:
print "%.2f" % ratio
except ZeroDivisionError:
print ptot
It looks like the reason this is happening is that your
ratio
assignment (dividingptot
andntot
) isn't contained within yourtry/except
block. You're not doing any division in thetry
block - why would aZeroDivisionError
be caught?If you were to change it to this:
this should remedy your error.