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 |
- Python Programming – Exception Handling
- Python Programming – Decision Making
- Using Python’s Tabnanny Module for Cleaner Code | The Tabnanny Module in Python with Example
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 |