You probably have a divide-by-zero error. Field Calculator definitely cannot divide when zero is the denominator, and sometimes will even throw errors with zero as the numerator. To get around this, click the "Select by attributes" button in the Attribute Table (top left corner, third from the left). Then type in this formula:
"Asian" <> 0 AND "Total" <> 0
This will select only records with no zeroes. When you use field calculator, it will only process these records. You can play around with other selections to get it right.
I have found that sometimes I need to include a single return
rather than in each if
/elif
/else
(I do not know why this is the case, but it has happened enough to now be my go to). Try setting a variable and returning just that variable at the end.
Codeblock:
def SpeedCalc(MTFCC):
x = 9999
if MTFCC == "S1400":
x = 25
elif MTFCC == "S1200":
x = 45
elif MTFCC == "S1100":
x = 65
elif MTFCC == "S1630":
x = 25
elif MTFCC == "S1730":
x = 15
return x
Expression:
SpeedCalc(!MTFCC!)
Alternatively create a python dictionary to store your lookup and return values, and return the values from that.
Codeblock:
def SpeedCalc(MTFCC):
myDict = {'S1400': 25, 'S1200': 45, 'S1100': 65, 'S1630': 25, 'S1730': 15}
x = 9999
if MTFCC in myDict:
x = myDict[MTFCC]
return x
Expression:
SpeedCalc(!MTFCC!)
A user tried to edit the answer with the following - I am including this as an additional option, however in my experience some python functions just don't work right in field calculator (as with the single vs multiple return
values above). Also I often prefer to have the additional lines, particularly for those new to python, as it's easier to read and understand what is actually happening in the code when learning.
def SpeedCalc(MTFCC):
myDict = {'S1400': 25, 'S1200': 45, 'S1100': 65, 'S1630': 25, 'S1730': 15}
return myDict.get(MTFCC, 9999)
Best Answer
You don't 'Dim' variables in python, you just declare and assign them. That said, your basic route is to set the parser to python and check Show Codeblock. In the Pre-Logic Script Code box, enter your function like this:
In your 'field =' box, enter:
In python , # means a comment. Indentation counts. If your calculation depends on other fields, pass those in as well. That should be straightforward with your background. In calling the function, the field name is bracketed by exclaimation (!) marks.