Matthew Pope
Matthew Pope

Reputation: 17

Bypassing ZeroDivisionError

How can I bypass the ZeroDivisionError and allow the program to continue whilst noting the 0 value?

for line in data:
  split=line.split()
  ptot=0
  ntot=0
  for pchar in "HKR":
    pchartotal=split[1].count(pchar)
    #print pchartotal
    ptot+=pchartotal
  for nchar in "DE":
    nchartotal=split[1].count(nchar)
    #print nchartotal
    ntot+=nchartotal
  print float(ptot)/float(ntot)

Upvotes: 0

Views: 1561

Answers (5)

mrkbutty
mrkbutty

Reputation: 599

Or you could just test and substitute the value when detecting a zero divisor;

print ('NA' if not ntot else float(ptot)/float(ntot))

Upvotes: 0

SMA
SMA

Reputation: 37023

Try:

try:
    print (1/0)
except ZeroDivisionError:
    print ("Yo that's divide by zero")

print ("Done cya")

Upvotes: 0

Himal
Himal

Reputation: 1371

You can use try{..} except{..} block

try:
    print float(ptot)/float(ntot)
except ZeroDivisionError:
   print 'divide by zero'

Handling Exceptions

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

you can use try-except :

for line in data:
  split=line.split()
  ptot=0
  ntot=0
  for pchar in "HKR":
    pchartotal=split[1].count(pchar)
    #print pchartotal
    ptot+=pchartotal
  for nchar in "DE":
    nchartotal=split[1].count(nchar)
    #print nchartotal
    ntot+=nchartotal
  try:
    print float(ptot)/float(ntot)
  except ZeroDivisionError :
    print "ZeroDivisionError: integer division or modulo by zero"

Upvotes: 0

twasbrillig
twasbrillig

Reputation: 18831

change this:

print float(ptot)/float(ntot)

to

try:
    print float(ptot)/float(ntot)
except ZeroDivisionError as err:
    print err

Upvotes: 1

Related Questions