Indentation is an empty space (whitespace) used at the beginning of any statement to start new paragraph.
indentation should be consistent throughout your code.
There are two types of indents:
Horizontal indents: spaces at the left 2 or 4 spaces.
Vertical indents(hanging indent): empty lines for splitting code into logical blocks.
Indentation in Python is mandatory.
Indentation in other languages like C,C++,Java etc is just for readability but in python, the indentation is a mandatory concept that should be followed when writing a python code, otherwise, python interpreter will thrown IndentationError.
Reason why indentation is important in python
because the indentation serves another purpose other than code readability
- To represent a block of code(Python treats the statements as a single block of code that have the same indentation level.)
- Without indentation, Python interpreter will get confused and does not know which statement to execute next or which statement belongs to which block.
- Indentation helps interpreter to understand the order in which each block/statement should be executed.
Python Indentation Rules
- The first line of Python code can’t have indentation, it will throw
- The best practice is to use 4 spaces for indentation.
- If you have multiple lines inside the if block, all the lines will need to be indented with same level otherwise You will get indentation error
- If there is colon at the end of a line, you will need to indent the next line/lines by ignoring your current level of indentation.
- If there is no colon, you should not indent the starting of a line.
- Python doesn't allow mixing tabs and spaces for indentation.
4-space or 2-space indentation
There are several styles .Pick a style that suits you, then use it consistently.
- K&R(Kernighan & Ritchie Style)
K&R(Kernighan & Ritchie Style) In K&R, single-line blocks do not have braces.