[GIS] Getting Null value error with Python Parser in field calculator

arcgis-desktopfield-calculatornullpython-parser

I'm trying to calculate the angle between two line segments in ArcMap 10.0. I have a point shapefile, so I'm using the xy coordinates of 3 successive points to calculate the angle. I'm trying to use Python in the Field Calculator, because I'm not good with Python and I'm not sure how to use the Python window. I finally got my code to work, but encountered an error when two successive points have the exact same coordinates. This creates a null value, and I get the error "The field is not nullable". I tried to put in an if statement to change nulls to 0s, but I still get the same error. I'm not sure if I'm identifying null values correctly, though, because I've found conflicting ways to represent them, and have tried "None" and ' ' and "Null" to no avail. It seems like there should be some way to just replace the angle value with 0 if the calculation returns a null value.

Does anyone have any ideas on how to get past the null values?

My code is below.

Record = 0
def turnangle(X3, Y3):
  import math
  global X1, Y1, X2, Y2, Record
  if Record == 0:  #first two rows aren't calculated
    angle = 0
    X1 = X3
    Y1 = Y3
  elif Record == 1: 
    angle = 0
    X2 = X3
    Y2 = Y3
  else:               #calculating angle
    BAx = X1 - X2
    BAy = Y1 - Y2
    BCx = X3 - X2
    BCy = Y3 - Y2
    dotprod = BAx * BCx + BAy * BCy
    lenA = math.sqrt((X1-X2)**2+(Y1-Y2)**2)
    lenB = math.sqrt((X2-X3)**2+(Y2-Y3)**2)
    angle = math.acos((dotprod)/(lenA*lenB))*180/math.pi
    X1 = X2       #advancing to next coordinates
    Y1 = Y2
    X2 = X3
    Y2 = Y3
  Record = Record + 1
  if angle is not None:  #Here is where I'm trying to substitute 0 for null values
    return angle
  else:
    return 0

Best Answer

This is a quick and easy way to get around the problem..but doesn't fix the error. This method works in the python window.

This design is often used inside of loops, and I'm unsure if the Field Calculator will accept it.

try:
 #the code you want to work goes here

except: #handles the error
    #print "an error occurred, but I can continue to work"
    pass
Related Question