Python Indentation
Table Of Contents
- What Is Indentation?
- Examples Of Python Indentation.
- Rules Of Indentation.
- Bad Indentation Examples.
(1) What Is Indentation?
- Most programming languages like C, C++, and Java use braces { } to define a block of code. Python, however, uses indentation.
- In simple terms indentation refers to adding white space before a statement.
- Without indentation, Python does not know which statement to execute next or which statement belongs to which block. This will lead to IndentationError.
- Indentation in other languages like C, C++, Java, 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.
(2) Examples Of Python Indentation
Example-1
Java Program
int time = 22;
if (time < 10)
{
System.out.println("Good morning.");
}
else if (time < 20)
{
System.out.println("Good day.");
}
else
{
System.out.println("Good evening.");
}
Python Program
time = 22;
if time < 10:
print("Good morning.");
elif time < 20:
print("Good day.");
else:
print("Good evening.");
Example-2
Java Program
int num1 = 22;
int num2 = 58
int addNumbers(num1,num2)
{
sum = num1 + num2
return sum
}
addNumbers(num1,num2)
Python Program
num1 = 22
num2 = 58
def addNumbers(num1,num2):
sum = num1 + num2
return sum
addNumbers(num1,num2)
(3) Rules To Follow
- Every time you don’t have to manually give spaces before all the statements, When you press ‘Enter’ after finishing a statement , indentation will be automatically given.
- The same block of statements comes under the same indentation. In the above example, the addNumber() function consists of two statements , which are having the same indentation, hence it comes under the same block.