1

I am attempting to populate fields on two different feature classes with different strings that I have stored in a list. I would like to just put the strings and feature classes into a for loop, but it has not been working. Here is my current script that makes the most sense to me:

def protectedlandslayer(PAD, NCED, counties, protectedFC):

    # set local variables in lists to prepare for looping
    ProtectedLands = [PAD, NCED]
    layers = ["pad", "nced"]
    county_lyr = arcpy.MakeFeatureLayer_management(counties, "counties_lyr")

    # select protected lands that intersect PA county boundaries and copy - populate
    # list with output feature classes to use in add field loop
    temp_featureclasses = []
    for FC, layer in zip(ProtectedLands, layers):
        outFC = "in_memory" + "\\" + layer
        layer1 = arcpy.MakeFeatureLayer_management(FC, layer)
        selection = arcpy.SelectLayerByLocation_management(layer1, "INTERSECT", county_lyr)
        protected_fc = arcpy.CopyFeatures_management(selection, outFC)
        temp_featureclasses.append(protected_fc)

    # add field to each dataset and populate with data source
    for name, f in zip(layers, temp_featureclasses):
    arcpy.AddField_management(f, "data_src", "TEXT", "", "",
    4, "Data Source", "", "", "")
        expression = str(name)
        arcpy.CalculateField_management(f, "data_src",
    expression, "PYTHON_9.3")

With this script, I am getting the following error:

ExecuteError: ERROR 000539: Error running expression: n  Traceback (most recent call last):   File "<expression>", line 1, in <module> NameError: name 'n' is not defined  Failed to execute (CalculateField)

Can anyone help me out?

  • 2
    There are missing parts in your question. Firstly what is variable n about which Python complains, and are the number of elements in temp_featureclasses and layers equal? – fatih_dur Aug 15 '16 at 14:22
  • second @faith_dur the error specifically states "name 'n' is not defined" where have you used the unassigned variable 'n' – spk578 Aug 15 '16 at 14:28
  • I am unaware of any unassigned 'n' that I used, which is why I am fairly baffled by this error. I have posted my full script with previous parts. Am I not seeing something obvious? – mmoore Aug 15 '16 at 14:33
5

The problem with your script is the expression. The expression must have the variable in single quotes since it is a string. There are a number of ways to format this. My favorite is as follows:

expression = """'{}'""".format(name)

Note the casting to string is not necessary since .format will do so automatically

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.