Select to view content in your preferred language

Python If statement for Code Block

4335
11
06-16-2011 01:07 PM
ChristopherBlinn
Emerging Contributor
Hello,

I am new to Python, and programming all together really.  I am building a model where I want the user to select from a drop down list a value for a parameter (Climate Variable).  I then want to use the Calculate Value tool to then get a string value for a variable that will be used to choose a field from a feature attribute table (PYCLIM).  I wrote this If Statement (which I believe is wrong) to do such and I am getting the 000989 syntax error on Line 1.

def getCLIMVAR(PYCLIM):
 climvar = str(%Climate Variable%):
  if climvar == "Current Temperature":
   PYCLIM = "CUR_TEMP"
   return PYCLIM
  elif climvar == "High Temperature":
   PYCLIM == "HI_TEMP"
   return PYCLIM
  elif climvar == "Low Temperature":
   PYCLIM == "LOW_TEMP"
   return PYCLIM
  elif climvar == "Wind Chill Temperature":
   PYCLIM == "CHILL_TEMP"
   return PYCLIM
  elif climvar == "Dew Point Temperature":
   PYCLIM == "DEW_TEMP"
   return PYCLIM
  elif climvar == "High Temperature":
   PYCLIM == "HI_TEMP"
   return PYCLIM
  elif climvar == "Relative Humidty":
   PYCLIM == "REL_HUMID"
   return PYCLIM
  elif climvar == "Solar Radiation":
   PYCLIM == "SOL_RAD"
   return PYCLIM
  elif climvar == "Wind Speed":
   PYCLIM == "WIND_SPEED"
   return PYCLIM
  else climvar == "Highest Wind Gust":
   PYCLIM == "HI_WIND_GUS"
   return PYCLIM


Any help would be appreciated.  Thank you in advance! If the code is horrible, please understand that I wrote this without ANY python experience.
Tags (2)
0 Kudos
11 Replies
JasonScheirer
Esri Alum
def getCLIMVAR(PYCLIM):
    climvar = str(%Climate Variable%)
    if climvar == "Current Temperature":
        PYCLIM = "CUR_TEMP"
        return PYCLIM
    elif climvar == "High Temperature":
        PYCLIM == "HI_TEMP"
        return PYCLIM
    elif climvar == "Low Temperature":
        PYCLIM == "LOW_TEMP"
        return PYCLIM
    elif climvar == "Wind Chill Temperature":
        PYCLIM == "CHILL_TEMP"
        return PYCLIM
    elif climvar == "Dew Point Temperature":
        PYCLIM == "DEW_TEMP"
        return PYCLIM
    elif climvar == "High Temperature":
        PYCLIM == "HI_TEMP"
        return PYCLIM
    elif climvar == "Relative Humidty":
        PYCLIM == "REL_HUMID"
        return PYCLIM
    elif climvar == "Solar Radiation":
        PYCLIM == "SOL_RAD"
        return PYCLIM
    elif climvar == "Wind Speed":
        PYCLIM == "WIND_SPEED"
        return PYCLIM
0 Kudos
DanPatterson_Retired
MVP Emeritus
Chris
although the amended "if" statement will work, you might want to start investigating Python dictionaries as a data structure to return/access information (aka values) based upon "keys".  Build the dictionary, then use it within a def to return the required values...makes a convoluted if statement much easier since you just need to update and reuse the dictionary without having to rebuild a big "if" statement.
0 Kudos
ChristopherBlinn
Emerging Contributor
def getCLIMVAR(PYCLIM):
    climvar = str(%Climate Variable%)
    if climvar == "Current Temperature":
        PYCLIM = "CUR_TEMP"
        return PYCLIM
    elif climvar == "High Temperature":
        PYCLIM == "HI_TEMP"
        return PYCLIM
    elif climvar == "Low Temperature":
        PYCLIM == "LOW_TEMP"
        return PYCLIM
    elif climvar == "Wind Chill Temperature":
        PYCLIM == "CHILL_TEMP"
        return PYCLIM
    elif climvar == "Dew Point Temperature":
        PYCLIM == "DEW_TEMP"
        return PYCLIM
    elif climvar == "Relative Humidty":
        PYCLIM == "REL_HUMID"
        return PYCLIM
    elif climvar == "Solar Radiation":
        PYCLIM == "SOL_RAD"
        return PYCLIM
    elif climvar == "Wind Speed":
        PYCLIM == "WIND_SPEED"
        return PYCLIM


Jason, thanks, so was just the indentation wrong? If so, what do I need to do in the future so I don't have this problem again?
0 Kudos
ChristopherBlinn
Emerging Contributor
Chris
although the amended "if" statement will work, you might want to start investigating Python dictionaries as a data structure to return/access information (aka values) based upon "keys".  Build the dictionary, then use it within a def to return the required values...makes a convoluted if statement much easier since you just need to update and reuse the dictionary without having to rebuild a big "if" statement.


Dan, thanks for the tip.  These "Keys"; can they access values generated by a tool parameter?  Those are the values I am referencing.

For instance, say I have a variable calculated from other input parameters called DATE (calculated by concatenating %MONTH%&"-"&%DAY%&"-"&%YEAR%; which are the input parameters).  This DATE value is needed to locate a file, using the DATE value in the file name.

I am using a code similar to the one above to take the input value of another parameter, and calculate a different string, which is then concatenated with the DATE value for the full file name.

If using dictionaries and keys will make this easier on me then I am all about using them.  Just didn't know if they would work for what I was doing.
0 Kudos
ChristopherBlinn
Emerging Contributor
I am really having trouble with these "If" statements...

I tried using the one Jason provided me as a template for another one and I keep getting the syntax error on Line 2.

def getTIME(TF):
 time == str(%Time Frame%)
 if time == "5 Minutes":
  TF == "5min"
  return TF
 elif time == "30 minutes":
  TF == "30min"
  return TF
 elif time =="1 hour":
  TF == "1hr"
  return TF
 elif time == "6 Hours":
  TF == "6hr"
  return TF
 elif time == "12 Hours":
  TF == "12hr"
  return TF
 elif time == "1 Day":
  TF == "1dy"
  return TF
 elif time == "3 Days":
  TF == "3dy"
  return TF
 elif time == "5 Days":
  TF == "5dy"
  return TF
 elif time == "1 Week":
  TF == "1wk"
  return TF
 elif time == "2 Weeks":
  TF == "2wk"
  return TF
 elif time == "1 Month":
  TF == "1mo"
  return TF
 elif time == "3 Months":
  TF == "3mo"
  return TF
 elif time == "6 Months":
  TF == "6mo"
  return TF
 elif time == "1 Year":
  TF == "1yr"
  return TF


I tried making it only 3 spaces on indentation and that still didn't help.
0 Kudos
ChrisSnyder
Honored Contributor
Probably too many cooks in the kitchen here, but:

In python, there is a difference between "=" and "==". The former is for assigning values, the latter is for comparing values. Also, there is no nead to "return" the TF variable in every if/elif statement - just return it once at the end after all teh conditional expresions have been evaluated.

BTW: Save yourself some time in the long run: Ditch ModelBuilder and go Python. The sooner the better.

But, in the mean time I do believe this should work, and if it doesn't, you should be closer to having the code iwork than you were before...

def getTIME(TF):
   time = str(%Time Frame%) #Note: I assume this line is some sort of model build integration thing - I don't really know what it's for though?
   if time == "5 Minutes":
      TF = "5min"
   elif time == "30 minutes":
      TF = "30min"
   elif time == "1 hour":
      TF = "1hr"
   elif time == "6 Hours":
      TF = "6hr"
   elif time == "12 Hours":
      TF = "12hr"
   elif time == "1 Day":
      TF = "1dy"
   elif time == "3 Days":
      TF = "3dy"
   elif time == "5 Days":
      TF = "5dy"
   elif time == "1 Week":
      TF = "1wk"
   elif time == "2 Weeks":
      TF = "2wk"
   elif time == "1 Month":
      TF = "1mo"
   elif time == "3 Months":
      TF = "3mo"
   elif time == "6 Months":
      TF = "6mo"
   elif time == "1 Year":
      TF = "1yr"
   else:
      TF = "SOL!"
   return TF
0 Kudos
ChristopherBlinn
Emerging Contributor
Yeah, I was told the same about ditching model builder from others who have been fortunate to know enough python.  Unfortunately I chose to take more GIS classes rather than programming when I was a student, but I would really like to learn more Python.

Here is the code output from the model I am building.  Maybe it will make more sense to have it posted.

# Import arcpy module
import arcpy

# Check out any necessary licenses
arcpy.CheckOutExtension("spatial")

# Script arguments
Climate_Variable = arcpy.GetParameterAsText(0)

Time_Frame = arcpy.GetParameterAsText(1)
if Time_Frame == '#' or not Time_Frame:
    Time_Frame = "5 Minutes" # provide a default value if unspecified

Month = arcpy.GetParameterAsText(2)
if Month == '#' or not Month:
    Month = "6" # provide a default value if unspecified

Day = arcpy.GetParameterAsText(3)
if Day == '#' or not Day:
    Day = "16" # provide a default value if unspecified

Year = arcpy.GetParameterAsText(4)
if Year == '#' or not Year:
    Year = "2011" # provide a default value if unspecified

# Local variables:
GIS_Files = "C:\\Users\\Chris\\Desktop\\WKU Summer\\Model\\GIS Files"
Tables_Workspace = "C:\\Users\\Chris\\Desktop\\WKU Summer\\Model\\Tables"
PYCLIM = Climate_Variable
v_PYCLIM__idw = PYCLIM
v_FILE_ = v_PYCLIM__idw
DBF = Time_Frame
MesoPoints = DBF
TF = Time_Frame
DATE = Month
Kentucky_shp = "C:\\Users\\Chris\\Desktop\\WKU Summer\\Projected Data\\Kentucky.shp"
v_DATE___TF__csv = "%DATE%_%TF%.csv"

# Process: Calculate Date Value
arcpy.CalculateValue_management("%Month%&\"-\"&%Day%&\"-\"&%Year%", "", "String")

# Process: Calculate Time Frame Name
arcpy.CalculateValue_management("getTIME(TF)", "def getTIME(TF):\\n   time = str(%Time Frame%)\\n   if time == \"5 Minutes\":\\n      TF = \"5min\"\\n   elif time == \"30 minutes\":\\n      TF = \"30min\"\\n   elif time == \"1 hour\":\\n      TF = \"1hr\"\\n   elif time == \"6 Hours\":\\n      TF = \"6hr\"\\n   elif time == \"12 Hours\":\\n      TF = \"12hr\"\\n   elif time == \"1 Day\":\\n      TF = \"1dy\"\\n   elif time == \"3 Days\":\\n      TF = \"3dy\"\\n   elif time == \"5 Days\":\\n      TF = \"5dy\"\\n   elif time == \"1 Week\":\\n      TF = \"1wk\"\\n   elif time == \"2 Weeks\":\\n      TF = \"2wk\"\\n   elif time == \"1 Month\":\\n      TF = \"1mo\"\\n   elif time == \"3 Months\":\\n      TF = \"3mo\"\\n   elif time == \"6 Months\":\\n      TF = \"6mo\"\\n   elif time == \"1 Year\":\\n      TF = \"1yr\"\\n   else:\\n      TF = \"SOL!\"\\n   return TF", "String")

# Process: Make DBF
arcpy.TableToTable_conversion(v_DATE___TF__csv, Tables_Workspace, "%DATE%_%TF%", "", "", "")

# Process: Create Mesonet Sites
arcpy.ConvertCoordinateNotation_management(DBF, MesoPoints, "LONG_", "LAT", "DD", "DD", "", "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision")

# Process: Calculate Field Name Value
arcpy.CalculateValue_management("getCLIMVAR(PYCLIM)", "def getCLIMVAR(PYCLIM):\\n    climvar == str(%Climate Variable%)\\n    if climvar == \"Current Temperature\":\\n        PYCLIM == \"CUR_TEMP\"\\n        return PYCLIM\\n    elif climvar == \"High Temperature\":\\n        PYCLIM == \"HI_TEMP\"\\n        return PYCLIM\\n    elif climvar == \"Low Temperature\":\\n        PYCLIM == \"LOW_TEMP\"\\n        return PYCLIM\\n    elif climvar == \"Wind Chill Temperature\":\\n        PYCLIM == \"CHILL_TEMP\"\\n        return PYCLIM\\n    elif climvar == \"Dew Point Temperature\":\\n        PYCLIM == \"DEW_TEMP\"\\n        return PYCLIM\\n    elif climvar == \"Relative Humidty\":\\n        PYCLIM == \"REL_HUMID\"\\n        return PYCLIM\\n    elif climvar == \"Solar Radiation\":\\n        PYCLIM == \"SOL_RAD\"\\n        return PYCLIM\\n    elif climvar == \"Wind Speed\":\\n        PYCLIM == \"WIND_SPEED\"\\n        return PYCLIM", "String")

# Process: IDW
arcpy.gp.Idw_sa(MesoPoints, "%PYCLIM%", v_PYCLIM__idw, "", "2", "VARIABLE 12", "")

# Process: Calculate File Name Value
arcpy.CalculateValue_management("%PYCLIM%_%DATE%_%TF%", "", "String")

# Process: Extract by Mask
arcpy.gp.ExtractByMask_sa(v_PYCLIM__idw, Kentucky_shp, v_FILE_)

0 Kudos
curtvprice
MVP Esteemed Contributor
I keep getting the syntax error on Line 2.

def getTIME(TF):
 time == str(%Time Frame%)
 if time == "5 Minutes":


You can't put model variables inside the Calculate Value codeblock. Here's how you do that:

Expression:
getTime("%Time Frame%") 

Code block:
def getTIME(TF):)
  if TF == "5 Minutes":
     (...)


You can read up on lists and dictonaries quickly in the Python tutorial. (I still go back to it at times to brush up.) Dan is right -- they are definitely the way to go with lookups like this:

dictTimes = {"Years":"yr","Days":"dy"}
lstPair = TF.split() # makes list: ["5","Years"]
shortName = lstPair[0] + dictTimes[lstPair[1]] # "5yr"
0 Kudos
ChristopherBlinn
Emerging Contributor
You can't put model variables inside the Calculate Value codeblock. Here's how you do that:

Expression:
getTime("%Time Frame%") 

Code block:
def getTIME(TF):)
  if TF == "5 Minutes":
     (...)


So, by making the list in a dictionary, I can then read the Time Frame variable, and based on that String value, get my shorthand string value that is used in the naming convention of my tables?
0 Kudos