Why is indentation important in Python?

PythonServer Side ProgrammingProgramming

Many a times it is required to treat more than one statements in a program as a block. Different programming languages use different techniques to define scope and extent of block of statements in constructs like class, function, conditional and loop. In C and C++ for example, statements inside curly brackets are treated as a block. Python uses uniform indentation to mark block of statements.

Before beginning of block symbol : is used. First and subsequent statements in block are written by leaving additional (but uniform) whitespace (called indent) . In order to signal end of block, the whitespace is dedented. Following example illustrates the use of indents in Python:

num = int(input("enter number"))
if num%2 == 0:
   if num%3 == 0:
      print ("Divisible by 3 and 2")
      print ("divisible by 2 not divisible by 3")
   if num%3 == 0:
      print ("divisible by 3 not divisible by 2")
      print  ("not Divisible by 2 not divisible by 3")

Note: It is important to ensure that all statements in a block at particular level should have same indentation.

Updated on 30-Sep-2019 09:00:06