[GIS] Writing an if then statement for if a parameter is selected (not Null) in Model Builder

arcgis-desktoparcmapmodelbuilderpython

I have a tool I'm trying to create in model builder. I have run into a problem as I have basically no experience with python. I'm trying to basically use the calculate value tool and an if then statement to determine if a model parameter (type String) has a value inputted to it by the user, if it does then go one direction in model builder and if not go another. Something to the effect of the picture below:
enter image description here

The Second picture is of the model with the properties of the string and the tool (in the lower right)

enter image description here

Best Answer

Edit: I checked the help for the calculate Value tool. It says: "Variables created in ModelBuilder can be used by this tool, but variables desired for use in the expression parameter cannot be connected to the Calculate Value tool. To use them in the expression, enclose the variable name in percent signs (%). For example, if you want to divide a variable named 'Input' by 100, your expression would be %Input%/100." So, ModelBuilder parameter names have to be surrounded by percent signs to be passed into the Calculate Value tool (It has to be %String%, not String). I have changed the code to show the correct syntax.

The String parameter is never Null, it is initialized as '', so the condition has been change to only return False when values of String are greater than ''. It returns true if String == ''.

You have several problems. In Python you must set up a def function to use a code_block. I have flipped your test logic so that it now tests for actual string values and not Null values. ModelBuilder may return '' for what you consider to be a Null String parameter value. So you may need to change the test to be just values greater than '', not values greater than or equal to ''. None should used to test for real Null values if you are dealing with field values from a table or a parameter from a script tool interface. You are also missing a colon at the end of your if statement as kttii mentioned. Also, this is setting a Boolean parameter based on the Data Type value you have chosen, not a text string, so your return values are wrong and you need to change them to return real Boolean values.

So the expression must change to:

nullTest(%String%)

So the code_block code must change to:

def nullTest(String):
    print("The value of String is {0}".format(String))
    if String > '':
        return False
    else:
        return True
Related Question