Indentation

Photo by Chris Ried on Unsplash

Indentation

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

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.

age = 18

if age == 18:
    print("You are now adult.")

Here in this example print has extra spacing, to keep it inside if statement. (This extra spacing is indentation)

Most of the programming languages like C, C++, and Java use braces { } to define a block of code. Python, however, uses indentation.

A code block (body of a function, loop, etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.

Generally, four whitespaces are used for indentation and are preferred over tabs. Here are few examples about right and wrong indentations,

  • Right Indentation
if 5 > 2:
    print("Five is greater than two!")
  • Wrong Indentation - You will get an error.
if 5 > 2:
print("Five is greater than two!")

  • Right Indentation
marks = 95
if marks > 90:
    print("Your Grade is A")
else:
    print("Your Grade is not A")
  • Wrong Indentation - You will get an error.
marks = 95
if marks > 90:
    print("Your Grade is A")
else:
 print("Your Grade is not A")

Hope this helps!