1

I have a model that converts a road network into a different schema for a different program. In one step of the model I am converting values for a field "Class". I wrote an If-Then-Else statement in Python but my syntax is off. Here is the code:

def gst(old_value):
    if old_value == 'P00':
        return A91:    
    elif old_value == 'P09':
        return A91:     
    elif old_value == 'P01':
        return A89: 
    elif old_value == 'P02':
        return A90:
    elif old_value == 'P03':
        return A90:
    elif old_value == 'P04':
        return A40:  
    elif old_value == 'P05':
        return A40:
    elif old_value == 'P06':
        return A40:  
    elif old_value == 'P10':
        return A40:
    elif old_value == 'P11':
        return A40:  

I am getting a syntax error from Line 3 in ArcMap (Error 000989). I am not sure if I need double quotes around my values or not or if I am ending the expression correctly. Can someone help me resolve the issues in my code?

4

On your return statement - remove the colon at the end. i.e.:

def gst(old_value):
    if old_value == 'P00':
        return A91

Also, if A91 is not an existing variable, and you want to have it as a string - you must enclose it in quotes -> 'A91'

  • Thank you so much, I removed the colon and then got the second error message about A89 not being an existing variable and then added the quotes and it solved it. – cbunn Jul 2 '14 at 17:08
2

Instead of using all those if...elif statements, you might find it easier to use a dictionary:

def gst(old_value):
    old = ['P00', 'P09', 'P01', 'P02', 'P03', 'P04', 'P05', 'P06', 'P10', 'P11']
    new = ['A91', 'A91', 'A89', 'A90', 'A90', 'A40', 'A40', 'A40', 'A40', 'A40']
    return dict(zip(old, new)).get(old_value)
  • I agree Paul, if I were doing this - a dictionary would be the way I would go too. I haven't seen the .get option in the dictionary before - thanks for the tip. – dklassen Jul 3 '14 at 18:01
  • 1
    @dklassen, using the .get() method is a bit better than the near equivalent dict(zip(old, new))[old_value] as the latter will return an error if the key is not found. .get() returns None if the key is not found, or will return a default value if a 2nd, optional parameter is passed to it. – Paul Jul 3 '14 at 18:06

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.