In this tutorial you will learn about the Python if…else Statement and its application with practical example.
Python if Statement
Block of statement executed only when a specified condition is true.
Table Of Contents−
Syntax:-
1 2 |
if expression: statement(s) |
Example:-
1 2 3 4 |
x = 20 if x > 10: print("x is greater") |
Output:-
1 |
x is greater |
Python if…else Statement
When we want to execute some block of code if a condition is true and another block of code if a condition is false, In such a case we use if….else statement.
Syntax:-
1 2 3 4 |
If expression statement(s) else: statement(s) |
Example:-
1 2 3 4 5 6 7 |
a = 10 b = 20 if a > b: print("a is greater than b") else: print("b is greater than a") |
Output:-
1 |
b is greater than a |
Python if…elif…else Statement
The if….elif…else statement is used to select one of among several blocks of code to be executed.
Syntax:-
1 2 3 4 5 6 |
if expression: statement(s) elif expression: statement(s) else: statement(s) |
Example:-
1 2 3 4 5 6 7 8 9 |
a = 10 b = 10 if a > b: print("a is greater than b") elif a == b: print("a and b are equal") else: print("b is greater than a") |
Output:-
1 |
a and b are equal |
Python Nested if statements
When there is an if statement inside another if statement then it is known as nested if else.
Syntax:-
1 2 3 4 5 6 7 8 9 10 |
if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else: statement(s) else: statement(s) |
Single Statement Condition
Example:-
1 2 |
a = 5 if (a == 5): print("The value of a is 5") |
Output:-
1 |
The value of a is 5 |