Product SiteDocumentation Site

2.2. Whitespaces and indentation

In Python whitespace is an important thing. We divide different identifiers using spaces.Whitespace in the beginning of the line is known as indentation, but if you give wrong indentation it will throw an error. Examples are given below:

>>> a = 12
>>>  a = 12
  File "<stdin>", line 1
      a = 12
          ^
          IndentationError: unexpected indent

Warning

There is an extra space in the beginning of the second line which is causing the error, so always look for the proper indentation.

You can even get into this indentation errors if you mix up tabs and spaces. Like if you use spaces and only use spaces for indentation, don't use tabs in that case. For you it may look same, but the code will give you error if you try to run it.

So we can have few basic rules ready for spaces and indentation.
  • Use 4 spaces for indentation.
  • Never mix tab and spaces.
  • One blank line between functions.
  • Two blank lines between classes.
There are more places where you should be following same type of rules of whitespace, they are like
  • Add a space after "," in dicts, lists, typles, and argument lists and after ":" in dicts.
  • Spaces around assignments and comparisons (except in argument list)
  • No spaces just inside parentheses.