python

Indentation

Unlike languages like C/C++/Java, Python provides no braces to indicate the block of code for classes/functions etc. Block of codes are denoted by line indentation as below

>>> if True:
         print 1
         print 2
         print 3
1
2
3
>>> if True:
         print 1
    print 2
IndentationError: unindent does not match any outer indentation level

From the above examples, it indicates that code under the same block should be indented by same amount or else indentation error will be thrown as above (print 2 should have been correctly indented as per print 1 since print 2 is still under if True block). Until you come out of the loop by pressing enter all the statements should follow same indentation. You can try it out using python prompt. You can also write program in a file and check indentation for the blocks.

Leave a Reply