Select to view content in your preferred language

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

278
4
07-09-2024 10:50 AM
by
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.

1 Solution

Accepted Solutions
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"``````
4 Replies
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"``````
by
New Contributor II

Thanks, really appreciate the help!

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"``````

by
New Contributor II

Thank you!