pythoninterpreterpython-2.6

Python - SyntaxError and IndentationError


I know that python is an interpreter language and it means that it interprets the code at run time, so why is that code gives me IndentationError?

def function(x):
    if x:

Does it check all the code before running it?


Solution

  • In Python, functions are objects.

    You get an error immediately because the Python interpreter wasn't able to construct a function object from your function definition due to improper syntax. In this case not having an indented block after your if statement.

    https://docs.python.org/2/tutorial/controlflow.html#defining-functions

    Creating a function instance happens before calling a function.

    >>> def errorOnCall(x):
    ...     return x / 0
    ... 
    >>> print errorOnCall
    <function errorOnCall at 0x7f249aaef578>
    

    Function object created due to no syntax error, but the function will raise an error when we invoke it.

    >>> errorOnCall(42)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in errorOnCall
    ZeroDivisionError: integer division or modulo by zero
    

    Now an error is thrown as soon as we invoke this function.

    >>> def errorOnDefinition(x):
    ...     if x:
    ... 
      File "<stdin>", line 3
    
        ^
    IndentationError: expected an indented block
    

    This error is thrown when we finish defining our function, but before we invoke it. The interpreter wasn't able to create a function instance from this invalid definition.