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.
Verbally:
“Hey, if this happens then perform this action.”
The general Syntax of If
, elif
and else
statements are as follows:
1 2 3 4 5 6 | if <condition1>: perform this statement1 elif <condition2>: 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.
1 2 3 4 | if <condition1>: 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.
1 2 3 4 | if marks >= 40: print("Pass") else: print("Fail") |
Let see some example more examples for clear understanding:
1 2 | if True: print("This is Inside of IF") |
output
1 | This is Inside of IF |
1 2 3 4 5 6 7 | 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
1 | value of x is 3 |
1 2 3 4 5 6 | role = "programmer" if role == "programmer": print("Helo! Programmer.") else: print("What do you do?") |
output
1 | Helo! Programmer. |
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.