Indentation and why is it important in Python

VenuMadhav
2 min readMar 19, 2024

--

🐍 Python Basics: Indentation🐍

Python Indentation

🔹 Indentation in Python

Indentation is a fundamental concept of Python because without properly indenting the Python code, As a result, python throws an IndentationError and the code will not get compiled.

🔹 Python Indentation

Python indentation involves adding white space before a statement to denote a specific block of code. In essence, all statements sharing the same level of indentation belong to the same code block.

// Without Indentation
// Bad Practice
flag = True
if(flag):
print("True")
else:
print("False")
// With Indentation
// Good Practice
flag = True
if(flag):
print("True")
else:
print("False")

Python indentation tells a Python interpreter that the group of statements belongs to a particular block of code. A block is a combination of all these statements. Block can be regarded as the grouping of statements for a specific purpose.

In languages like C, C++, and Java, braces { } are used to define a block of code. In contrast, Python uses indentation to highlight blocks of code. Whitespace is used for indentation in Python. 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.

i = 0
while(10 > i):
i += 1
print(i)

The code above seems to have a small syntax issue. Although the logic looks good, the while statements are not in the same code block, which is causing the Python interpreter to throw an IndentationError. To fix this issue, you need to ensure that the while statements are in the same code block.

i = 0
while(10 > i):
i += 1
print(i)

In Python, to indicate a block of code, you must indent each line of the block by the same amount of whitespace. For example, the two lines of code in the while loop are both indented four spaces. It is necessary to indicate which block of code a statement belongs to. Therefore, Python structures its code by using indentation.

Note: Python uses 4 spaces as indentation by default. However, the number of spaces is up to you, but a minimum of 1 space has to be used.

That’s all for now, Python pals! Remember, proper indentation is key to writing clean and readable Python code! 🚀💻 #PythonBasics #CodeWithMe

--

--

VenuMadhav

Software Developer || Python - PHP - Node.js. .. Transitioning into Data Science ⚛