What is Indentation in Python?

Indentation is used in Python to signify a code block. The spaces at the start of a code line are referred to as indentation. Python indentation is a way of telling a Python interpreter that the group of statements belongs to a particular block of code. A block is a combination of all these statements. Whitespace is used for indentation in Python. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right.

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.