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 is 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. You use them when you want some other statements or code to execute when the condition in the
if block doesn’t satisfy, otherwise, you can use single
if statement alone.
You can also write multiple
elif statements like in the above example to execute different set of statements under different conditions. But there can be only one
else statement at the end of one group of if-else logic.
Let’s see some examples to have better understanding of
else statements in Python.
Examples using 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 you can represent it in python using if and else:
if marks >= 40: print("Pass") else: print("Fail")
if True: print("This is Inside of IF")
Output: This is Inside of IF
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
if with multiple
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 program to perform some action depending on the specified condition.
- Only a single
elifstatement in order of a group of if-else statements executes, if all the above conditions are false.
elsestatement executes 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.