Pulling my hair out here...I'm trying to rebuild a for loop in a field calculator tool in modelbuilder. No matter what I try, the for loop only returns the last value of the iteration. This should be so simple, but I've been stuck for hours! Tried all sorts of reconfigurations.
I have several fields with H,M,L or N values. Each of those should be assigned a score, which is then summed and returned for the new field. No matter what I do, the returned value is caculated ONLY based on the last field in the list as if I had the sum = 0 line inside the For loop...but I don't.
sum = 0
for f in fields:
if f == "H":
score = 5
elif f == "M":
score = 3
elif f == "L":
score = 1
score = 0
sum = sum + score
flds = ['H', 'L', 'M', 'N'] def CalcFVScore(flds): sum = 0 for f in flds: if f == "H": sum += 5 elif f == "M": sum += 3 elif f == "L": sum += 1 else: sum += 0 return sum CalcFVScore(flds) Out: 9
As a field calculation, all it is going to do is sum each value in that row.
It will not cycle through all the rows and produce some big cumulative sum.
That is not how field calculations work. The work a row at a time.
I don't have any trouble running your code when I test it. However, you may want to change your variable name, as sum is a built-in function, and perhaps it's throwing something off. I replaced "sum" → "s" and it ran just fine.
It runs just fine for me as well, the problem is the solution is wrong. It only returns the result of the last field in the list. If I change the list, the result changes...it's not summing the cumulative values from the for iterations, only the value from the last iteration.
confusion... you only show 4 fields in your example. Hopefully those are the actual field names.
You need to provide the "Field Names".... Your example suggests that those are the field names, not the values in those fields.
If you want to sum across the row for the number of occurences of H, M, L, N etc.... then you need to field the field names into the fields list
I think it's solved...first I found a domain issue in the geodatabase- the field had both a domain assigned as well as a subtype with domain. Running again I had the same issue, but then I deleted all the fields from the expression, and re-entered them one by one, running each time to see if it worked. After adding them all back it seems to be returning correct results.
I cannot explain it, thanks for taking a look. I did use Dan's version to simplify the code which is a good improvement.