Using code block in field calculator

4009
11
Jump to solution
03-04-2019 06:24 AM
Thomvan_Oijen
New Contributor II

Hello Community,

I'm completely at a lost here. I have tried all possible combinations and was trying to figure out how to get this to work but it just doesn't work for me.

The thing I am trying to accomplish is the following:

I have 5 fields with a or b answers (1 or 0) and 5 fields with the correct solution. (also 1 or 0).

Q1-5 and A1-5.

I also have 5 fields with a Weight

W1-5.

I am trying to find a floating value of 0-1 based on the answer. This goes in the field Betrouwbaarheid

This is what I have so far, which is to you very clearly incorrect. But I have tried a lot of different types of formatting without avail.

Note: It's updated!

Expression:
calc(!Q1!, !Q2!, !Q3!, !Q4!, !Q5!, !A1!, !A2!, !A3!, !A4!, !A5!, !W1!, !W2!, !W3!, !W4!, !W5)

Code block:
def calc(Q1, Q2, Q3, Q4, Q5, A1, A2, A3, A4, A5, W1, W2, W3, W4, W5):
    if Q1 == A1:
        c1 = 1
    else:
        c1 = 0

    if Q2 == A2:
        c2 = 1
    else:
        c2 = 0
    
    if Q3 == A3:
        c3 = 1
    else:
        c3 = 0
        
    if Q4 == A4:
        c4 = 1
    else:
        c4 = 0

    if Q5 == A5:
        c5 = 1
    else:
        c5 = 0
    
    betr = (c1 * W1 + c2 * W2 + c3 * W3 + c4 * W4 + c5 * W5) / (W1 + W2 + W3 + W4 + W5)
    return betr‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Thanks to the people below a part was resolved. My new code gives no syntax errors.

However, i still get an error when trying to do a field calculation.

 ERROR 000539:   File "<expression>", line 1
    calc(, , , , , , , , , , , , , , )
         ^
SyntaxError: invalid syntax
 Failed to execute (CalculateField).

I hope anyone can shed me some light into how this codeblock programming works. It's a complete and utter mystery to me.

Tags (2)
11 Replies
DanPatterson_Retired
MVP Emeritus

Scott, it never got past the first line since a trailing ! was missing... see my previous post

Thomvan_Oijen
New Contributor II

Thanks all! Problem is resolved.

Apparently, since I was using a Join, I had to specify the table name in the expression. So no !W5! but !Database.W5!

0 Kudos