Consider a situation where you are required to make a correct decision based on a particular condition. You can do this with the help of if statements or if-else statements.
Generally, when there are more than two choices then if-else ladder is used. Let us analyze them in detail.
1. If Statement
This statement is used to execute one or more statements depending on whether s condition is true or false.
if(conditions): statement 1 statement 2
Let us consider a program to see the working of if statements.
Program : Check whether a given number is even or odd using if statements only.
num = 4 if(num%2 == 0): print("Even") if(num%2==1): print("Odd")
In the above program we have used two if statements of which first is for checking even number and second one is for checking odd number. Here, for num=4, we get the answer from first if, but even after getting the output interpreter will check other conditions as well. This is an inefficient approach. To save our program from unwanted longer execution we use if-else statements.
2. If-else Statement
This statement follows following idea :
if this then do-this else do-this
In other words, if-else statements executes a group of statements when a condition is True, else it executes another group of statements.
if(conditions): statement 1 else: statement 2
When a given condition is True, then Statement-1 will execute. When a given condition is False, then Statement-2 will execute.
Let us code the same program of even-odd checker using if-else.
num = 4 if(num%2 == 0): print("Even") else: print("Odd")
So, if-else is faster than if statement.
3. if … elif … else Statement
There may be a situation, when you want to test multiple conditions and drive the output accordingly. In such cases where there are wide range of statements, if-elif-else statements are useful.
if(condition1): statement 1 elif(condition2): statement 2 else: statement 3
When condition1 is True, then Statement-1 will execute. When a given condition2 is True, then Statement-2 will execute. If both conditions are False, then Statement-3 will execute.
Note : elif statement in Python is same as else-if statement in other languages.
Let us consider a program to see the working of if-elif-else statements.
Program : To check whether a given number is zero, positive or negative.
n=4 if(n==0): print("Zero") elif(n>0): print("Positive") else: print("Negative")
Talking about Indentation –
Indentation refers to the spaces that are generally used in the beginning of a statement. Statements with same Indentation belong to same group. Indentation plays a vital role in Python programing as it defines the hierarchy of statements.