Search code examples
pythondivide-by-zero

Altered program, ZeroDivisionError


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

Solution

  • It looks like the reason this is happening is that your ratio assignment (dividing ptot and ntot) isn't contained within your try/except block. You're not doing any division in the try block - why would a ZeroDivisionError be caught?

    If you were to change it to this:

    ratio = 0
    try:
        ratio = float(ptot) / float(ntot)
        print "%.2f" % ratio
    except ZeroDivisionError:
        print ptot
    

    this should remedy your error.