Select to view content in your preferred language

Learning Python- Needing help with If/Then Field Calculator Script

244
4
Jump to solution
4 weeks ago
Gtech301
New Contributor II

Hello! I am very very new to Python and am needing help creating a script for Field Calculator and am having trouble finding an online resource- hoping someone here could help me! I created a script that populates a new field based off of existing attributes in an existing field but am needing to add a caveat that if another case is true, then this other condition supersedes all other conditions.

ie I currently have something along the lines of: 

def Reclass(field1):

if (field 1=='x'):

return "1"

if (field 1 =='y'):

return "2"

else:

return "3"

But I want to add something that says that no matter what is in field 1, if field 2 == y, return 4: a condition to supersede all the other conditions. 

Thanks in advance!

0 Kudos
1 Solution

Accepted Solutions
AlfredBaldenweck
MVP Regular Contributor

Should be straightforward.

Try something like this:

def reclass(field1, field2):
    # Check field2 and then immediately exit if it works.
    if field2 == "y":
        return 4
    # Start checking field1.
    if field1 == "x":
        return "1" 
    elif field1 == "y":
        return "2" 
    else:
        return "3"

View solution in original post

4 Replies
AlfredBaldenweck
MVP Regular Contributor

Should be straightforward.

Try something like this:

def reclass(field1, field2):
    # Check field2 and then immediately exit if it works.
    if field2 == "y":
        return 4
    # Start checking field1.
    if field1 == "x":
        return "1" 
    elif field1 == "y":
        return "2" 
    else:
        return "3"
Gtech301
New Contributor II

Thanks, really appreciate the help!

0 Kudos
BlakeTerhune
MVP Regular Contributor

The conditions are evaluated in order so put the most important one first and use elif for the other conditions. You'll also need to update the parameters in your function to accept Field2.

# Expression
Reclass(!Field1!, !Field2!)

# Code Block
def Reclass(field1, field2):
    if field2 == "y":
        return "4"
    elif field1=="x":
        return "1"
    elif field1 =="y":
        return "2"
    else:
        return "3"

 

Gtech301
New Contributor II

Thank you!

0 Kudos