a) Basic Example

Guido Van Rossum used the concept of indentation for grouping the statements. The reason for selecting indentation was its ability to provide elegance and clarity to the programmer. Colons (:) are used for declaring indented code block. Example is shown below

class trial_Class:
    #Every function belonging to a class must be indented equally
    def __init__(self):
      name = "trial"
    def someFunction(self, b):
      #everything belonging to a function must be indented
      if b > 5:
        return True
      else:
        return False
Click here to practice

If a function is not indented to the same level it will not be considered as part of parent class.

for letter in 'CodingXone':
    # loops are indented and nested conditions starts a new indentation
    if letter == 'e' or letter == 's':
        break

print('Current Letter :', letter)
Click here to practice

The recommended indentation is 4 spaces but tabs or spaces can be used hand to hand as longs as they are consistent. It is strongly discouraged to combinely use tabs and spaces to prevent from any error.

b) How indentation is parsed?

Whitespaces are being handled by lexical analyzer before being parsed. The lexical analyzer uses a stack based storage for storing the indentation level. At the beginning stack contains just the value 0, which denotes the leftmost position. Whenever a nested block begins, the new indentation level is pushed on the stack, and an “INDENT” token is inserted into the token stream which is passed to the parser. There can never be more than one “INDENT” token in a row (IndentationError).

When a line is encountered with smaller indentation level, values are popped from the stack until the value equal to new indentation level is on the top (if none is found a syntax error occurs). For each popped value, a “DEDENT” token in generated. Obviously there can be mutiple “DEDENT” tokens in a row.

The lexical analyzer skips empty lines (those containing only whitespaces and possibly comments), and will never generate either “INDENT” or “DEDENT” tokens for them.

At the end of the source code, “DEDENT” tokens are generated for each indentation level left on the stack, until just the 0 is left.

if foo:
    if bar:
        x = 42
 else:
    print foo
Click here to practice

is analyzed in the following manner:

Output : <if> <foo> <:>                    [0]
<INDENT> <if> <bar><:>                     [0, 4]
<INDENT> <x> <=> <42>                      [0, 4, 8]
<DEDENT> <DEDENT> <else> <:>               [0]
<INDENT> <print> <foo>                     [0, 2]
<DEDENT>

The parser then handles the “INDENT” and “DEDENT” tokens as block delimiters.

c) Indentations Errors

The spacing should be uniform throughout. Incorrect indentation can cause an Indentation error or cause program to behave unexpected. Following program will raise an IndentationError.

a = 9
if a > 7:
    print "Coding"
else:
    print "Xone"
  print "done"
Click here to practice

If the line following a colon is not indented, an IndentationError will also be raised:

if True:
print "true"
Click here to practice

If you add indentation where it doesn’t belong, an IndentationError will be raised:

if True:
    a = 6
        b = 5
Click here to practice

If indentation is not done properly it can affect the functionality. In this example None is returned instead of expected False:

def isEven(a):
    if a%2 == 0:
        return True
        return False # this line should be even with the if 
print isEven(7)
Click here to practice

Comments are useful when the coding steps are not clear. For details click here.

Scroll to Top