else statements in python allow us to perform different tasks depending on certain conditions.
These are also known as conditional statements because they decide which statements should run and which should not.
Verbally: “Hey, if this happens then perform this action.”
The general syntax of
else statements are as follows:
if <condition1>: perform this statement1 elif <codition2>: perform this statement2 elif <codition3>: perform this statement3 ... else: perform this last statement
else statements are optional, so if we don’t want any other statement to execute (in case the condition doesn’t satisfy), we can use single
if statement alone.
We can write multiple
elif statements with different conditions, but there can be a maximum of one
else statement at the end of one group of if-else logic.
Let’s see some examples to learn different combinations of
else statements in Python.
Example 1: if and else
Let’s say if a student passes the examination if he or she gets more than or equal to 40 marks otherwise fails. This is how we can represent it in python using if and else:
if marks >= 40: print("Pass") else: print("Fail")
Example 2: if with True condition
if True: print("This is Inside of IF") #output: This is Inside of IF
Example 3: if, elif and else
x=3 if x==2: print("value of x is 2") elif x==3: print("value of x is 3") else: print("value of x is not matching")
Output: value of x is 3
Example 4: if with multiple elif
def greet(role): if role == "prime minister": print("Hello Sir!") elif role == "soldier": print("Yes Sir!") elif role == "programmer": print("I can hack NASA with HTML!") greet("programmer")
Output: I can hack NASA with HTML!
Characteristics of if-else in Python
ifstatement allows the computer to perform some action.
elifstatement is executed if the above statements are false.
elsestatement is executed only if all the above conditions (including
elif) are false.
Tip: Use if-elif-else when only one of the given tasks/statements should need to be executed depending on certain conditions.