Question

I have a simple loop which gets stuck on a division by zero error. I am running a bool to filter out zero-value denominators, but for some reason the bool I used isn't working. Can someone please help? I am using python 2.6.5

Here is a sample from my code:

for i in range(0,len(lines)):
    line = lines[i]
    line = line.split(";")
    leansz = line[9]
    FW = line[34]
    FS = line[35]  
    print "FS: %s  %s"%(FS,type(FS))  #troubleshooting the denominator and its type
    if FS == "0":  #I have tried FS == 0 and FS == "0" to no avail
        print 'FS == "0"' #checking if bool is working
        continue  #return to top of loop if denominator is zero
    LnSzRa = float(leansz)/(float(FS)/2)  #division by zero error   

Here is a sample of what is returned and then the error:

FS: 184
  <type 'str'>
FS: 1241
  <type 'str'>
FS: 2763
  <type 'str'>
FS: 1073
  <type 'str'>
FS: 971
  <type 'str'>
FS: 0
  <type 'str'>
Traceback (most recent call last):
  File "mpreader.py", line 50, in <module>
    LnSzRa = float(leansz)/(float(FS)/2)
ZeroDivisionError: float division
Was it helpful?

Solution

Your FS value is a string that includes the newline character from the file still, so test for a string value:

if FS == '0\n':

or strip the newline:

    if FS.strip() == '0':

or turn FS into a float first:

if float(FS) == 0:

or strip line while splitting:

line = line.strip().split(';')

Further tips:

  • Just loop over lines directly; don't use range():

    for line in lines:
        line = line.strip()
        # do something with `line`
    

    Even if you still need an index as well, you use enumerate() to generate the index:

    for i, line in enumerate(lines):
        line = line.strip()
        # do something with `line` and `i`.
    
  • You can use the csv module to handle splitting data files into rows:

    import csv
    
    with open(somefile, 'rb') as inputfile:
        reader = csv.reader(inputfile, delimiter=';')
        for row in reader:
            leansz, FW, FS = map(float, (row[9], row[34], row[35]))
            if not FS: continue
            LnSzRa = leansz / (FS / 2)
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top