python - For Loop with Bool -
i have simple loop gets stuck on division 0 error. running bool filter out zero-value denominators, reason bool used isn't working. can please help? using python 2.6.5
here sample code:
for 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 denominator , type if fs == "0": #i have tried fs == 0 , fs == "0" no avail print 'fs == "0"' #checking if bool working continue #return top of loop if denominator 0 lnszra = float(leansz)/(float(fs)/2) #division 0 error
here sample of returned , 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
your fs
value string includes newline character file still, test string value:
if fs == '0\n':
or strip newline:
if fs.strip() == '0':
or turn fs
float first:
if float(fs) == 0:
or strip line
while splitting:
line = line.strip().split(';')
further tips:
just loop on
lines
directly; don't userange()
:for line in lines: line = line.strip() # `line`
even if still need index as well, use
enumerate()
generate index:for i, line in enumerate(lines): line = line.strip() # `line` , `i`.
you can use
csv
module handle splitting data files rows:import csv open(somefile, 'rb') inputfile: reader = csv.reader(inputfile, delimiter=';') row in reader: leansz, fw, fs = map(float, (row[9], row[34], row[35])) if not fs: continue lnszra = leansz / (fs / 2)
Comments
Post a Comment