Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why is indentation important in Python?
Indentation indicates the spaces or tabs placed at the beginning of a line of code to indicate the block structure. In many programming languages, indentation is used to improve code readability.
In Python, indentation is the key part of the syntax. It is used to define the blocks of code, such as loops, conditionals, and functions. If indentation is not used properly in Python, it results in the IndentationError, causing the program to fail.
Code Without Proper Indentation
Let's see what happens when we use an if-else statement without proper indentation ?
a = 5
if a > 2:
print("a is greater than 2")
else:
print("a is less than or equal to 2")
The output of the above program is ?
IndentationError: expected an indented block after 'if' statement
Code With Proper Indentation
Now let's use the same if-else statement with proper indentation. The print statements are indented under the if and else blocks, indicating the code that belongs to each condition ?
a = 5
if a > 2:
print("a is greater than 2")
else:
print("a is less than or equal to 2")
The output of the above program is ?
a is greater than 2
Indentation Rules in Python
Python follows these key indentation rules:
- Use 4 spaces per indentation level (recommended)
- Be consistent − don't mix tabs and spaces
- All statements in the same block must have the same indentation level
- Nested blocks require additional indentation
Example with Nested Blocks
Here's an example showing nested indentation with a loop inside an if statement ?
numbers = [1, 2, 3, 4, 5]
if len(numbers) > 0:
print("The list contains:")
for num in numbers:
if num % 2 == 0:
print(f" {num} is even")
else:
print(f" {num} is odd")
The output of the above program is ?
The list contains: 1 is odd 2 is even 3 is odd 4 is even 5 is odd
Conclusion
Indentation in Python is mandatory and defines code structure. Always use consistent indentation (4 spaces recommended) to avoid IndentationError and ensure your code executes properly.
