0

I have used try - except and it works, but I was wondering if we can perform a similar function with for - if and else.

# check for "NA" values, ignore the entries which have them
    # index: DeptTime = 4,Deptdelay = 15, Arrtime = 6, ArrDelay = 14
    for index in flight_data[1:]:
        try:
            x_dept.append(int(index[4]))
            y_dept.append(int(index[15]))
            x_arr.append(int(index[6]))
            y_arr.append(int(index[14])) 
        except ValueError:
            pass

For instance, can we do something like this to get the exactly same answer?

 # check for "NA" values, ignore the entries which have them
        # index: DeptTime = 4,Deptdelay = 15, Arrtime = 6, ArrDelay = 14
        for index in flight_data[1:]:
            if index[4] =='NA' or index[15] == 'NA' or index[14] =='NA' or index[6] == 'NA':
             pass
             else:
                x_dept.append(int(index[4]))
                y_dept.append(int(index[15]))
                x_arr.append(int(index[6]))
                y_arr.append(int(index[14])) 
Jerald.IFF
  • 63
  • 5
  • I know it says java, but the concept holds here. – cs95 Oct 16 '17 at 19:13
  • Yes, you can do it this way and it will work fine. For a more general solution, you could say `if not index[4].isdigit()` instead of `if index[4] == 'NA'`, to also catch other cases of non-numeric content. – John Gordon Oct 16 '17 at 19:20
  • Also, your two code samples don't quite behave the same way. If, say, the first value is an integer and the second one is 'NA', the try/except method will append one value to x_dept and then hit the exception, where the if/else method will not, as it explicitly checks all four values before trying to append. – John Gordon Oct 16 '17 at 19:26
  • So it does work to: `for index in flight_data[1:]: if not index[4].isdigit(): pass elif not index[15].isdigit(): pass elif not index[6].isdigit(): pass elif not index[14].isdigit(): pass else: x_dept.append(int(index[4])) y_dept.append(int(index[15])) x_arr.append(int(index[6])) y_arr.append(int(index[14]))` But it just gives wrong value that's all. – Jerald.IFF Oct 16 '17 at 20:20

0 Answers0