Reputation: 17
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
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
Reputation: 37023
Try:
try:
print (1/0)
except ZeroDivisionError:
print ("Yo that's divide by zero")
print ("Done cya")
Upvotes: 0
Reputation: 1371
You can use try{..} except{..}
block
try:
print float(ptot)/float(ntot)
except ZeroDivisionError:
print 'divide by zero'
Upvotes: 0
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
Reputation: 18831
change this:
print float(ptot)/float(ntot)
to
try:
print float(ptot)/float(ntot)
except ZeroDivisionError as err:
print err
Upvotes: 1