What is Indentation in Python

Whitespace is used for indentation in Python. Unlike many other programming languages which only serve to make the code easier to read, Python indentation is mandatory. One can understand it better by looking at an example of indentation in Python.

Role of Indentation in Python

A block is a combination of all these statements. Block can be regarded as the grouping of statements for a specific purpose. Most programming languages like C, C++, and Java use braces { } to define a block of code for indentation. One of the distinctive roles of Python is its use of indentation to highlight the blocks of code. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right.  

Example 1:

The lines print(‘Logging on to w3wiki…’) and print(‘retype the URL.’) are two separate code blocks. The two blocks of code in our example if-statement are both indented four spaces. The final print(‘All set!’) is not indented, so it does not belong to the else-block. 

Python3




# Python indentation
 
site = 'gfg'
 
if site == 'gfg':
    print('Logging on to w3wiki...')
else:
    print('retype the URL.')
print('All set !')


Output

Logging on to w3wiki...
All set !

Example 2:

To indicate a block of code in Python, you must indent each line of the block by the same whitespace. The two lines of code in the while loop are both indented four spaces. It is required for indicating what block of code a statement belongs to. For example, j=1 and while(j<=5): is not indented, and so it is not within the while block. So, Python code structures by indentation.

Python3




j = 1
while(j <= 5):
    print(j)
    j = j + 1


Output

1
2
3
4
5

Statement, Indentation and Comment in Python

Here, we will discuss Statements in Python, Indentation in Python, and Comments in Python. We will also discuss different rules and examples for Python Statement, Python Indentation, Python Comment, and the Difference Between ‘Docstrings’ and ‘Multi-line Comments.

Similar Reads

What is Statement in Python

A Python statement is an instruction that the Python interpreter can execute. There are different types of statements in Python language as Assignment statements, Conditional statements, Looping statements, etc. The token character NEWLINE is used to end a statement in Python. It signifies that each line of a Python script contains a statement. These all help the user to get the required output....

What is Indentation in Python

Whitespace is used for indentation in Python. Unlike many other programming languages which only serve to make the code easier to read, Python indentation is mandatory. One can understand it better by looking at an example of indentation in Python....

What are Comments in Python

...

Types of comments in Python

...