Why is indentation important in Python?


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")
   else:
      print ("divisible by 2 not divisible by 3")
else:
   if num%3 == 0:
      print ("divisible by 3 not divisible by 2")
   else:
      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

663 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements