Python Indentation
What is Code Indentation in Python?
Python uses indentation (spaces before code line) to indicate a block of code statement, while other programming languages use {} (curly braces) to indicate the same.
- Indentation is a fundamental part of Python language's syntax.
- Code indentation requires a careful attention to avoid syntax errors.
Convention of Python Code Indentation
The standard convention is to use four spaces for each level of indentation.
Minimum one space or tab for indentation can be used for identation but it is not generally recommended.
Look at the following example where the if statement is the beginning of a conditional block. The colon : at the end of the if statement indicates the start of a new indented block. Therefore the line print("This condition is true.") is indented under the if statement with four spaces.
Example of Indentation
Output of the above example
This condition is true.
Code in the same block does not require code indentation as shown the following example.
Example of Indentation
Output of the above example
This condition is true.
15 is greater than 13.
Syntax Error For Code Indentation
If you do not indent your code properly, you will get an IndentationError as shown in the following example.
Look at the following example where no space has been kept before the line print("This condition is true.").
Example of Syntax Error For Indentation
Output of the above example
File "", line 2 print("This condition is true.") ^ IndentationError: expected an indented block after 'if' statement on line 1
IndentationError: expected an indented block after 'if' statement on line 1: The 'IndentationError' refers that the code block after 'if' statement needs to be indented.
Python Compiler For Live Practice
Practice the above Python code in the following Python Editor. Write python code with indentation in the following code editor and click Execute button. The output will be displayed in Python Code Output section.
Python Editor