绕过ZeroDivisionError

时间:2014-11-10 08:07:37

标签: python

如何绕过ZeroDivisionError并允许程序继续注意0值?

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)

5 个答案:

答案 0 :(得分:1)

改变这个:

print float(ptot)/float(ntot)

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

答案 1 :(得分:0)

您可以使用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"

答案 2 :(得分:0)

您可以使用try{..} except{..}阻止

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

Handling Exceptions

答案 3 :(得分:0)

尝试:

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

print ("Done cya")

答案 4 :(得分:0)

或者你可以在检测到零除数时测试并替换该值;

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