Python Indentation


An indentation or indent is an empty space at the beginning of a line that signals the start of a new logical block in a Python program. Many programming languages such as c and c++ uses curly braces to describe a block of code, indentation used just for readability in them.

Indentation is very important in Python and other programming languages that use this technique.

Example of using indentation in Python

The following example shows the use of indentation in Python if-else statements.

num=10
if num>=5:
     print("The given number is greater than 5")
elif num==5:
     print("The given number is equal to 5")
else:
     print("The given number is less than 5")

As you can see the highlighted part in the image below, shows the use of indentation in Python code.

Python IndentationError

All the code in Python is arranged with the use of correct whitespaces. When no indentation is used where it required or if not used in a correct way, the Python interpreter will through IndetationError.

Now if we run the above code in the following way –

num=10
if num>=5:
print("The given number is greater than 5")
elif num==5:
     print("The given number is equal to 5")
else:
     print("The given number is less than 5")

This will through IndentationError, you can see this in the image below.

Whenever you use encounter this error, check whether you have used whitespaces correctly before a line of code.

How many spaces you should use?

The number of spaces that you use before a line of code is up to you but you should use at least one whitespace. Remember to use the same number of spaces before each line of code that falls in the same block of code.

Conclusion

This is all about the use of indentation in Python. Now if you have a query then write use in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.