AnsweredAssumed Answered

Passing a number variable as global in python

Question asked by dljayasekera on Sep 7, 2017
Latest reply on Sep 8, 2017 by dljayasekera



I want to loop the below process for multiple years so tested with one year. I am getting an error when it tries to change the (YEAR) as calculate field as a number variable with the corresponding year. Cannot understand what I am doing wrong here. Everything else up to line 29 is working. Problem is inside the code block section. 


Any help is greatly appreciated. 


Thanks in advance. 


ExecuteError: ERROR 000539: Error running expression: getClass(1998.0) 
Traceback (most recent call last):
  File "<expression>", line 1, in <module>
  File "<string>", line 4, in getClass
NameError: global name 'yr' is not defined

Failed to execute (CalculateField).


years = [1997] 
# Write the selected features to a new featureclass
for year in years:
arcpy.CopyFeatures_management("PLSS_KS_All_GCS", r"C:/Users/Desktop/Flood/KS_All.gdb/PLSS_KS_All_WklyPrSum_PRISM_800m_" + str(year)+ "_new")

# Set environment settings
  arcpy.env.workspace = "H:/PRISM_800m_weekly_sum_tif"

# Set local variables
inPointFeatures = r"C:/Users/Desktop/Flood/KS_All.gdb/PLSS_KS_All_WklyPrSum_PRISM_800m_" + str(year)+ "_new.shp"

# Set local variables
inRasterList = [["Week_1_Sum" + str(year)+ "_10.tif", "Oct_PCPwk1"],
["Week_2_Sum" + str(year)+ "_10.tif", "Oct_PCPwk2"],
["Week_3_Sum" + str(year)+ "_10.tif", "Oct_PCPwk3"],
["Week_4_Sum" + str(year)+ "_10.tif", "Oct_PCPwk4"],
["Week_5_Sum" + str(year)+ "_10.tif", "Oct_PCPwk5"],
["Week_1_Sum" + str(year)+ "_11.tif", "Nov_PCPwk1"],
["Week_2_Sum" + str(year)+ "_11.tif", "Nov_PCPwk2"]]

# Check out the ArcGIS Spatial Analyst extension license

# Execute ExtractValuesToPoints
ExtractMultiValuesToPoints(inPointFeatures, inRasterList, "BILINEAR") #NONE

fieldName = "YEAR"
expression = "getClass(!YEAR!)"
codeblock = """def getClass(YEAR):
global yr
if YEAR >= 1998:
return yr
return -9999"""

# Execute AddField
#arcpy.AddField_management(inTable, fieldName, "SHORT")

# Execute CalculateField
arcpy.CalculateField_management(inPointFeatures, fieldName, expression, "PYTHON_9.3", codeblock)