python

Indentation means in Python

We are describing indentation usage and meaning in this post. We refers the spaces added before code as indentation in Python.

# Correct indentation
def my_func():
    print('hello')

# Incorrect indentation (Will throw IndentationError)
def my_func():
print('hello')

Unlike other programming languages, Indentation is very important in Python. If you will not properly use the indentation in Python, it will throw error.

In the code example, we have created two functions. First function will be executed successfully because we have used spaces or tab before print() function. The second function will throw an error because we have not added space before print() method.

The exception that occur due to indentation error

  File "main.py", line 2
    print('hello')
    ^
IndentationError: expected an indented block

In Python, Indentation is necessary to create a block of code.

You do not need to apply multiple spaces to add indentation before your code. But atleast one space is required.

How to resolve IndentationError

To resolve indentation in Python, You need to use proper spaces and tabs in your code blocks. Remember to use same spaces and tabs for same code block.

Was this helpful?