Python Indentation

Popular programming languages like C, C++, C#, Java uses the curly brackets {} in order to define code blocks for namespaces, for, while, function, and related implementation. Python has a bit different mechanism to define code blocks which are called indentation.

Indentation

Indentation is creating Python code blocks by using spaces to the left. As an example, the developer uses 3 spaces from the start of the line for the first level indentation. Another 3 spaces for the 2nd level indentation etc. This space count should be consistent and the same for all indentation implementation. Using indentation force the Python code to be more readable and easy to grasp but also create problems if the space count is not the same or tabs can break the code block and Python interpretation.

Indentation Example

Lets make some Python indentation example in order to understand better. Every block definitions like for, while, function requires indentation in order to create and code block for this statements.

for i in range(1,5):
   print("We will check ",i)
   if(i%2==0):
      print(i,"is diviseable to 2")
  • for i in range(1,5): line do not have indentation but using the for loop requires indentation definition.
  • print("We will check ",i) line indentation 3 spaces which makes it the code clock of the previous for loop.
  • if(i%2==0): line is the code block of the for loop and requires 2nd level indentation because of if definition.
  • print(i,"is diviseable to 2") is the 2nd level indentation which is the previous if statement code block.

Indentation Space Count

The space count for the indentation is very important because it should be the same and consistent throughout the Python file or script. Generally, 3 spaces are used for each level of the indentation. Using the tab will create errors because the indentation requires spaces or whitespaces which are not the same as tabs even they may seem the same. If you use tab as indentation you should continue to use tab for every indentation but this will create problems in general. Python 3 does not allow to use of both tabs and spaces for indentation.

Indentation Errors

Especially newcomers to the Python programming language will face indentation errors in the first months of their learning process. Even there may be different indentation errors the most popular and generic indentation error is "IndentationError: unexpected indent" which is like below.

Indentation Errors

Leave a Comment