Does python rely on indentation?


Python Indentation

Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Python will give you an error if you skip the indentation:

The number of spaces is up to you as a programmer, but it has to be at least one.

Example

if 5 > 2:
 print("Five is greater than two!") 
if 5 > 2:
        print("Five is greater than two!") 

Try it Yourself »

You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:

Example

Syntax Error:

if 5 > 2:
 print("Five is greater than two!")
        print("Five is greater than two!")

Try it Yourself »




Learn about Indentation in Python.

Overview

Indentation in Python Programming is simply the spaces at the beginning of a code line. Indentation in other languages like c, c++, etc., is just for readability, but in Python, the indentation is an essential and mandatory concept that should be followed when writing a python code; otherwise, the python interpreter throws IndentationError.

To understand this topic, you should have some knowledge of the following Python Programming topics:

  • Python Syntax
  • Comments in Python
  • Scope of Variable in Python

Scope of article

  • In this topic, we are going to learn about Indentation in Python.
  • We will learn a few rules on indentation with some example codes.
  • Then, we will discuss some advantages and disadvantages of indentation.

What is Indentation in Python

Indentation is the leading whitespace ( spaces and tabs ) before any statement in Python. The reason why indentation is important in python is that the indentation serves another purpose other than code readability. Python treats the statements with the same indentation level (statements with an equal number of whitespaces before them) as a single code block. So whereas in languages like c, c++, etc. a block of code is represented by Curly braces { }, in python a block is a group of statements that have the same Indentation level i.e same number of leading whitespaces.

Does python rely on indentation?

Below are some of the observations that can be made from the above figure:
  • All the statements which are on the same level of Indentation(Same no of whitespaces before them) belong to a single block, so from the above diagram, statements in line 1, line 2, and line 7 belong to a single block, and the block has the zero or lowest level of indentation. Statements 3 and 5 are indented one step, forming another block at the first level of indentation. Similarly, statements 4 and 6 are indented two steps, so they together form another block at the second level of indentation.
  • Below the line 2 statement, which is an if statement, statements 3 and 5 are indented one step; hence, they belong to a single block. And since line 2 is an if statement, the block indented below the if forms the body of if. So here, the body of the if statement at line 2 includes all the lines that are indented below it, i.e., lines 3,4,5 and 6.
  • Now that we know that statement at line numbers 3,4,5 and 6 forms the body of the if statement at line 2. Let us understand the indentation for them. Statements at 3 and 5 are uniformly indented, so they belong to a single block (block2 from the interpretation), and they will be executed one by one.
  • Statement at line 4 makes up the body of the if statement at line 3, as we know any statements that are indented below an if form the body of if statement, similarity the statement at line 6 makes up the body of else statement at line 5.
  • This is how the indentation helps define the blocks and also to identify to which statements the block belongs.
  • The execution starts at line 1 followed by the statement at line 2; if the condition is evaluated and in case it returns true, then control goes inside the body of the if statement, which brings statements 3,4, 5, and 6 to the picture.
    • Now, the statement at line 3 is executed, and if the condition is evaluated, in case it returns true, then line 4 is executed, after which control goes to line 7. If the condition at line 3 returns false, then control goes to another statement that is line 5, and then line 6 is executed, followed by the statement at line 7.
  • In case condition at line number 2 returns false, the control skips lines 3, 4, 5, and 6 and goes to the statement at line 7.

Examples

Example 1: Below is an example code snippet with the correct indentation in python.

name = 'Rahul'
  
if name == 'Rahul':
   print('WelCome Rahul..')
   print('How are you?')
else:
   print('Dude! whoever you are ')
   print('Why you here?')
 
print('Have a great day!')

Output:

WelCome Rahul..
How are you?
Have a great day!

Explanation:

  • The name variable gets assigned to Rahul in the first statement
  • Now the statement if name == ‘Rahul’: is evaluated, it returns true, so it executes the body of the if, which is the indented next two statements below the if statement. The two statements inside the body are print(‘WelCome Rahul..’) and print(‘How are you?’) and they get executed.
  • Once the statement gets executed the else part is skipped and control goes to the next statement which is print(‘Have a great day!’), which is executed.
  • In this program, the statements inside the bodies of if and else are indented.

Example 2: Below is an example code snippet with correct indentation.

i = 1
while(i <= 6):
    print("Value is " + str(i))
    i = i + 1

Output:

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is 6

Explanation:

  • Variable i is initialized to 1 in the first statement
  • Now while(i <= 6) is executed which is true, so the body of the while is executed. The body of the while is all the statements that are indented below the while loop.
  • So print (“Value is” + str(i)) and i = i + 1 are executed.
  • This process is repeated till the while condition returns false.
  • Here the statements print (“Value is ” + str(i)) and i = i + 1are uniformly indented to form a block and also the body of the while statement.

How to indent your python code

Let us walk through how to indent a python code by taking a simple example.

Example: Check if a given number is even or odd and if it’s zero print neither even nor odd

Let us discuss the approach step-wise:

  • The first step is to assign an integer variable with the input number.
  • Write an if-else block to check if the input number is 0,
    • If It is not zero, Inside the if block, write another if-else (inner if-else) block to check the condition number % 2 == 0(This is the even check for a given number)
      • If the condition number % 2 == 0 is true, print that the number is even.
      • If the condition number % 2 == 0 is false, then the number is odd in the else block print.
  • If the number is zero, Inside the outer else block print that the given number is neither even nor odd.

Program:

number = 50

if(number != 0):
 if(number % 2 == 0):
   print("Given number is Even")
 else:
   print("Given number is Odd")
else:
 print("Given number is neither even nor odd")

Output:

Explanation:

  • At the first level of the indentation line, numbers 1, 3, and 8 belong to a single block.
  • Execution starts from line 1 and is followed by line 3.
  • At line 3, the if condition is evaluated, and since the number != 0 returns True, control goes inside the if condition, which is the indented block of statements below the if at line 3.
  • Inside the if block
    • Line no 4 and 6 are on the same indentation level( Second indentation level), so they belong to a single block
    • The if condition at line no 4 is evaluated, and since 50 % 2 == 0 returns True, control goes inside the if statement at line 4. So control goes to line 5, and the print statement is executed.
  • Control late skips the else block inside the inner if-else and the else block of the outer if-else and goes to the statement below line 9.

How to avoid python indentation errors

  1. Python will throw an indentation error if you skip the indentation. For Example, the below code would throw IndentationError: expected an indented block error:

Wrong Indentation(Error):

if( 1 == 1):
print("This is test code")

With Correct Indentation:

if( 1 == 1):
  print("This is test code")

  1. The number of whitespaces in indented code should be the same for the same block of code. Otherwise, Python will throw IndentationError: unexpected indent.

Wrong Indentation(Error):

if( 1 == 1):
 print("This is test code")
     print("This is test code1")

With Correct Indentation:

if( 1 == 1):
 print("This is test code")
 print("This is test code1")

  1. Indentation on the first line of code is not allowed. Python will throw IndentationError: unexpected indent.

Wrong Indentation(Error):

if( 1 == 1):
print("This is test code")
print("This is test code1")

With Correct Indentation:

if( 1 == 1):
 print("This is test code")
 print("This is test code1")

  1. Indented statements should have an attaching statement; for instance, all the statements indented below form a block and belong to the if statement. This is applicable for while, for, functions , classes, etc in python. The below example makes this point clear.

Wrong Indentation(Error):

if( 1 == 1):
   print("This is test code")
 
 print("This is test code1")

The above program will throw the “IndentationError: unindent does not match any outer indentation level” error because the last print statement, which is indented, does not match with any other indentation(no attaching outer statement). In the program, hence this will throw an error.

Correct Indentation:

if( 1 == 1):
   print("This is test code")
 
   print("This is test code1")

Here the last print statement’s indentation matches with the indentation of the print statement below if block. Hence here, the outer attaching statement is the if statement.

Python Indentation Rules

  • Python uses four spaces as default indentation spaces. However, the number of spaces can be anything; it is up to the user. But a minimum of one space is needed to indent a statement.
  • The first line of python code cannot have an indentation.
  • Indentation is mandatory in python to define the blocks of statements.
  • The number of spaces must be uniform in a block of code.
  • It is preferred to use whitespaces instead of tabs to indent in python. Also, either use whitespace or tabs to indent; intermixing of tabs and whitespaces in indentation can cause wrong indentation errors.

Benefits of Indentation in Python

  • Indentation of code leads to better readability, although the primary reason for indentation in python is to identify block structures.
  • Missing { and } errors that sometimes popup in c,c++ languages can be avoided in python; also the number of lines of code is reduced.

Disadvantages of indentation in Python

  • Code must be carefully indented with proper no of whitespace and ensure that whitespaces' uniformity is maintained in a single block. If the number of lines in python code is huge, sometimes this can become tedious if the indentation is corrupted by chance.
  • Without the use of good editors/Ide’s that help with the indentation, writing a python code, especially huge lines of code, is sometimes a tedious task because, for each line, we should make a type in the indentation as well.

Conclusion

We have reached the end of the article. Python indentation is something that is a foundation concept for any new python programming, understanding how indentation works are the first step before you can start writing code in python.

Does Python depend on indentation?

The first line of python code cannot have an indentation. Indentation is mandatory in python to define the blocks of statements. The number of spaces must be uniform in a block of code. It is preferred to use whitespaces instead of tabs to indent in python.

Does Python ignore indentation?

Python Indentation can be ignored by line continuation which means we can write the code in one line but it makes the code difficult to read and understand, so it is good to indent. After writing the above code (Python block Indentation), Ones you will print “ Welcome ” then the output will appear as a “ Welcome “.

Does Python only accepts 4 space per indentation?

Python doesn't care, as long as you're consistent. So if you start using four spaces for your indent, you always need to use four spaces. For example, in this snippet of code, we can see that the first indent has four spaces, but the second indent has only two. And you can see that the code doesn't line up.

How does Python handle indentation?

How to solve an indentation error in Python?.
Check for wrong white spaces or tabs. ... .
Be certain that the indentation for a specific block remains the same throughout the code, even if a new block is introduced in the middle. ... .
Go to your code editor settings and enable the option that seeks to display tabs and whitespaces..

Tải thêm tài liệu liên quan đến bài viết Does python rely on indentation?