2

Help! I think I am missing something that must be so obvious but I cannot figure out what I am doing wrong. Here's some background:

I have one short integer field (MajAspNum) that has values 1-10. I have another text field (Direction) that needs to be filled. I am trying to use the Field Calculator to calculate it but am not succeeding in any way. I should know what I'm doing but I just can't seem to make it work.

Pre-logic Script Code:

def des(num):
if num = 1:
    return "Flat"
elif num = 2:
    return "North"
elif num = 3:
    return "Northeast"
elif num = 4:
    return "East"
elif num = 5:
    return "Southeast"
elif num = 6:
    return "South"
elif num = 7:
    return "Southwest"
elif num = 8:
    return "West"
elif num = 9:
    return "Northwest"
elif num = 10:
    return "North"
else:
    return "N/A"




Direction = 
des (!MajAspNum!)

It gives me a GeoProcessing error of invalid syntax on line 2. I have tried just selecting by attributes in the attributes table and then using field calculator more simply on just those but that gives me a very weird error that literally makes no sense. I'm hoping my error is a really obvious fix to someone out there!

Vince
  • 20,017
  • 15
  • 45
  • 64
cAnna01
  • 258
  • 1
  • 3
  • 11
  • The answers are correct; however the issue for which you were getting the error message is that tests for equality require two equals signs: if num ==1: – Tom Jan 20 '16 at 03:41

3 Answers3

4
def des(num):
 aList=['Flat', 'N', 'NE', 'E','SE','S','SW','W','NW','N']
 if num in range(1,11):return aList[num-1]
 return 'N/A'

Alternatively select valid records and use:

['Flat', 'N', 'NE', 'E','SE','S','SW','W','NW','N'][ !MajAspNum! -1]
FelixIP
  • 22,922
  • 3
  • 29
  • 61
3

A switch statement is ideal for what you want to do. Since Python doesn't support switch statements, you can use dictionary mapping to accomplish the same thing.

def des(num):
    the_dict = {1: 'Flat',
                2: 'North',
                3: 'Northeast',
                4: 'East',
                5: 'Southeast',
                6: 'South',
                7: 'Southwest',
                8: 'West',
                9: 'Northwest',
                10: 'North'
    }
    return the_dict.get(num, 'N/A')
Ken
  • 596
  • 2
  • 8
  • I think this is the best solution. Switch statement (or in this case, a dictionary), is the right call. – Fezter Jan 19 '16 at 22:06
1

here it is in vbs, i can do it in python later when i have the time.

dim result1

if [MajAspNum] = "1" then
     result1 = "flat"

Elseif [MajAspNum]  = "2" then
     result1 = "north"

Elseif [MajAspNum]  = "3" then
     result1 = "northeast"

...

Else result1 = "N/A"

end if

^^ codeblock

Direction = result1

I found this searching the site, Writing conditional (if/then) statements into Field Calculator of ArcGIS for Desktop using Python parser? it has the correct syntax for python.

ed.hank
  • 3,862
  • 1
  • 14
  • 35