If, elif and else statement 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.
“Hey, if this happens then perform this action.”
The general Syntax of
else statements are as follows:
: perform this statement1 elif : perform this statement2 else: perform this statement3
If there is only one condition depending on which you want to execute some statements then
elif is not required.
: perform this statement1 else: perform this statement3
Let’s say, if a student gets more than or equal to 40 marks then he passes the examination or else he fails. This is how we can represent it in python using if and else.
if marks >= 40: print("Pass") else: print("Fail")
Let see some example more examples for clear understanding:
if True: print("This is Inside of IF")
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")
value of x is 3
role = "programmer" if role == "programmer": print("Helo! Programmer.") else: print("What do you do?")
Characteristics of if-else in Python
- if statement allows the computer to perform some action.
- elif statement is executed if above statements is false.
- else statement is executed only when all the conditions are false.
Use if-elif-else in that situation when only one of the given tasks/statements can be executed depending on some conditions.