1

I have been trying to calculate a field using code block in a python script. For this I am trying to set a variable for the code block called "codeblock". What I ended up finding was some interesting indentation errors before finally getting it to work. Below are two examples of code, one that didn't work and one that did work. I would like to find out why one works and the other does not.

Example 1:(DID WORK)

Codeblock = """def RemoveNull(X):
 if X is None:
 return 0
 else:
 return X""" 

Example 2:(DID NOT WORK)

Codeblock = """
def RemoveNull(X):
 if X is None:
 return 0
 else:
 return X"""

The only difference between the two was where I placed the "def RemoveNull(X):"

Does anyone know why example 1 worked and example 2 did not? I would guess it has to do with the triple quotation marks, but I am unsure.

Bera
81.7k14 gold badges85 silver badges199 bronze badges
asked Apr 11, 2018 at 18:00
3
  • What GIS software are you using? Commented Apr 11, 2018 at 18:14
  • I am creating the python script in Pyscripter. To be used for ArcGIS 10.4. Commented Apr 11, 2018 at 18:22
  • in field calculator correct? Commented Apr 11, 2018 at 18:23

2 Answers 2

2

How do you think computers know when to go to the next line?

If you think about the difference between your code examples you have put in a carriage return or new line character. A carriage return character is invisible but places text on the next line. You will see \n everywhere with respects to python as that is the new line character.

So now you know you have put in a special character this explains why one fails and the other does not, you started your function with a new line character...

answered Apr 11, 2018 at 19:43
2
  • Awesome, thank you for the answer. That seems to make sense to me. Commented Apr 11, 2018 at 21:08
  • 1
    I've run into this field calculator oddity from time to time. Personally I wouldn't expect that new line to cause a problem because, well, why would a new line be a problem in Python? Option 2 is better formatted and more readable and from the 'principle of least surprise' I would expect it to work. Instead you get an 'indentation error on line 2'. Commented May 4, 2018 at 12:15
0

As noted by Hornbydd, the difference is caused by a line break. If you place example two in parentheses it can be made to work too. For example:

Codeblock = (
 """def RemoveNull(X):
 if X is None:
 return 0
 else:
 return X""")
answered Jan 18, 2019 at 18:16
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.