ArcPy Python – Fix Indentation Errors When Calculating Field in Python Using Codeblock

arcpyfield-calculatorpython

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.

Best Answer

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...

Related Question