This was a fun python problem to illustrate the workflow on.
I might update this later to cleanup the exception handling when you calculate the field. The comments show what I am doing at each step of the script.
import arcpy, sys
#Let's start with using a workspace. This will make later work easier
arcpy.env.workspace = "C:\\gislab2\\Python\\take_home\\"
shapefile = "USCancer2000.shp"
field_name = "Henry1"
#Validate field name
field_name = arcpy.ValidateFieldName(field_name)
#Make sure our shapefile exists
if not arcpy.Exists(shapefile):
sys.exit("Input shapefile " + shapefile + " does not exist in workspace " + arcpy.env.workspace + ". Cannot continue.")
#Check if field exists already, and delete it if it does
if (len(arcpy.ListFields(shapefile, field_name)) == 1):
#Add the field
#Rather than use CalculateField, the logic involved makes this better suited for a cursor
cursor = arcpy.UpdateCursor(shapefile)
for row in cursor:
#Get the value of each of our fields, and put them into variables
c1 = row.getValue("Cnt1")
c2 = row.getValue("Cnt2")
c3 = row.getValue("Cnt3")
p1 = row.getValue("Pop1")
p2 = row.getValue("Pop2")
p3 = row.getValue("Pop3")
#check for missing values, assuming that non-missing values are all greater than or equal to zero
#also make sure we are not going to divide by zero
try: #The try allows us to catch errors so we can bail out and still set the field to zero
if((min(c1,c2,c3,p1,p2,p3) < 0) or ((p1+p2+p3) == 0) ):
field_value = 0
print "Calculating (" + "+".join([str(c1),str(c2),str(c3)]) + ")/(" + "+".join([str(p1),str(p2),str(p3)]) + ")" #This is a debugging line, can remove once works properly.
field_value = 1.0 * (c1+c2+c3)/(p1+p2+p3)
#If something goes wrong, set the value to 0 still
field_value = 0
#Set the value of Henry1 for just this row
print "Setting '" + field_name + "' to " + str(field_value) #This is a debugging line, can remove once works properly.
#At this point, we look back to the type of the for-in statement and do the next row in the shapefil
#Do cleanup at the end