Python Programming - Indentation

Python Programming – Indentation

The majority of the programming languages such as C, C++, and Java use braces {} to define a block of code, whereas, the Python language uses indentation. The block of a code starts with the first unindented line. The amount of indentation is up to the programmer. Moreover, it must be consistent throughout that block. Generally, a tab of 5 white spaces is preferred. For instance, consider code 2.1.,

Code: 2.1. Illustration of indentation in Python

for i in range (0 , 10 ) :
print ( i )
if i==5:
break
output
0
1
2
3
4
5

indentation also makes the code more readable. Another instance is given in Code 2.2. as follows:

Code 2.2. Illustration of indentation in python

if True:
print (‘Hello’)
a=5
output
Hello

Incorrect indentation will result in IndentationError as displayed in Fig. 2.1. We can see that code 2.2.results in Hello whereas while making incorrect indentation an error occurs “expected an indented block” for the code given in Code 2.3.

Code: 23. Illustration of indentation in Python 3

if True:
print(‘Hello’)
a=5

Python Programming - Indentation chapter 2 img 1

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *