This tutorial provided an overview of indentation in Python, a significant aspect of the language's syntax used to define code blocks. Python uses indentation to indicate the scope of code blocks such as functions, loops, conditionals, classes, etc. Let's understand the role and importance of indentation in python in detail.
Indentation is significant in Python, a programming language known for its readability and simplicity indentation groups statements that belong together, such as a loop or a conditional statement. Python uses indentation instead of brackets to indicate blocks of code. Incorrect indentation could result in an error. ❌ Similar to a hopscotch game - hopping on one foot and after that the other, following the lines of the board, Python takes after the lines of code within the program. On the off chance that the lines of code were not enough indented, Python would not be able to execute the code within the correct order, and the program would not work as intended:
For example, Let's write a simple program that prints the numbers from 1 to 10 using a for loop:
for i in range(1, 11):
print(i)
In this program, the print(i) statement should be indented one level to the right of the for statement. This indentation indicates that the print(i) statement is part of the loop and should be executed for each value of I in the range. 🔁 To ensure proper execution of the program, it is crucial to include indentation before the print(i) statement.
for i in range(1, 11):
print(i)
This program will also raise an IndentationError because the print(i) statement is not indented to the right of the for statement. Python cannot determine which statements are part of the block.
If you're coding in Python, one of the most important things to remember is the proper indentation of your code. Good Python indentation is necessary to make your code readable and easy to understand, both for yourself and others who may read your code later.
For Example:
If we are writing a code if a particular number is even or odd:
number=20
if number!=0:
if number%2==0:
print('Number is Even')
else:
print('Number is Odd')
else:
print('Number is neither even nor odd')
The above example shows that the second if-else statement is a code block under the first if-else statement because we have given a proper indentation for that code block.
if x > 0:
print("Positive number") # Correctly indented
else:
print("Non-positive number") # Raises an IndentationError
if True:
print("Use 4 spaces") # Consistent indentation
print("Inconsistent indentation") # Error: IndentationError
# PEP 8 Recommended Indentation
def greet():
print("Hello!") # 4 spaces
if True:
print("Python is awesome!") # Nested block with 4 more spaces
if condition1:
print("Block 1")
if condition2:
print("Nested Block")
print("Back to Block 1")
print("Outside all blocks")
# Mixing tabs and spaces
def function():
\tprint("Tab used here") # Tab character
print("Spaces used here") # Raises TabError
# Hanging Indentation
result = (first_value
+ second_value
+ third_value) # Aligned indentation
if True:
# This is a comment
print("Indented code")
Proper indentation ensures that blocks of code execute in the right context.
# Example
number = 5
if number > 0:
print("Positive number")
else:
print("Non-positive number")
Output:
Positive number
Incorrect indentation leads to a syntax error since Python relies on indentation to define code blocks.
# Example
number = 5
if number > 0:
print("Positive number") # Improper indentation
else:
print("Non-positive number")
Error:
IndentationError: expected an indented block
Nested blocks should have progressively deeper indentation to maintain structure.
# Example
number = 5
if number > 0:
print("Positive number")
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
Output:
Positive number
Odd number
Mixing tabs and spaces within the same block leads to a TabError.
# Example
def greet():
\tprint("Hello!") # Tab used here
print("Welcome!") # Spaces used here
Error:
TabError: inconsistent use of tabs and spaces in indentation
Loops with proper indentation execute nested and outer loops without issues.
# Example
for i in range(3):
print(f"Outer Loop {i}")
for j in range(2):
print(f" Inner Loop {j}")
print("Back to Outer Loop")
Output:
Outer Loop 0
Inner Loop 0
Inner Loop 1
Back to Outer Loop
Outer Loop 1
Inner Loop 0
Inner Loop 1
Back to Outer Loop
Outer Loop 2
Inner Loop 0
Inner Loop 1
Back to Outer Loop
Correctly indented functions ensure proper execution of statements within their block.
# Example
def add_numbers(a, b):
result = a + b
print(f"Sum of {a} and {b} is {result}")
return result
add_numbers(3, 4)
Output:
Sum of 3 and 4 is 7
Comments do not affect indentation and can be placed anywhere.
# Example
if True:
# This is a comment
print("Indented code")
# Another comment
print("Still indented")
print("Outside the block")
Output:
Indented code
Still indented
Outside the block
Multi-line statements require proper alignment for readability and execution.
# Example
total = (1 + 2 +
3 + 4 +
5)
print("Total:", total)
Output:
Total: 15
Classes with correct indentation ensure that methods and attributes are scoped properly.
# Example
class MyClass:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}!")
obj = MyClass("Python")
obj.greet()
Output:
Hello, Python!
In Python, an indentation error occurs when spaces or tabs are not placed properly. Python uses indentation to group statements. If the interpreter finds issues with the spaces or tabs, it can halt execution. The error message indicates the line number and nature of the error. To fix it, check each line for proper indentation, ensuring 4 whitespaces for each level of indentation.
def my_function():
print("Hello, Data Science Enthusiasts!")
print("This line has an extra space.")
my_function()
In this example, the second print statement contains an additional space before it, which leads to an indentation error.
def my_function():
print("Hello,Data Science Enthusiasts!")
print("This line uses both spaces and tabs.")
my_function()
In this example, the second print statement has an indentation error because it uses a mix of spaces and tabs for indentation.
def my_function():
print("Hello, Data Science Enthusiasts!")
print("This line has inconsistent indentation.")
my_function()
In this example, the second print statement has inconsistent indentation compared to the first print statement, which causes an indentation error.
def my_function():
print("Hello, Data Science Enthusiasts!")
print("This line is incorrectly indented.")
print("This line is back to the correct indentation.")
my_function()
In this example, the second print statement needs to be indented correctly. This causes an indentation error for the entire block of code. To avoid most indentation errors in Python code, pay attention to these errors and follow the tips I mentioned earlier.
Here are a few best practices for using indentation in Python: 🔎
In conclusion, space could be a principal perspective of Python utilized to demonstrate the structure of the code. Python's dependence on space has been questionable, but it is by and large considered a supportive highlight that creates code more readable and simpler to get it. By taking after the best hones for space, you'll be able to guarantee that your Python code is steady and simple to preserve.
Answer: C: Indentation is used to group statements that belong together.
Answer: B. To indicate the start and end of a block of code.
Answer: B. It helps to improve code readability.
Top Tutorials
Related Articles