Python if...else Statement
If-Else statements in Python are a component of conditional statements.
There are four types of conditional statements in Python:
- The if statement
- The if-else statement
- The if…elif…else Statement
- The nested-if statement
If Statement
The if statement is employed to run a code block when a specific condition holds.
Syntax:
if (condition):
# block of code to be executed if the condition is true
Example:
number =
8
if
(number > 5):
print("Number is greater than 5")
Output:
Number is greater than 5
If...else statement
The if.else statement is employed for executing one block of code when a given condition is true and another block of code when the condition is false.
Syntax:
if (condition):
# block of code to be executed if the condition is true
else:
# block of code to be executed if the condition is false
Example:
number =
8
if
(number > 5):
print("Number is greater than 5")
else:
print("Number is not greater than 5")
Output:
Number is greater than 5
if…elif…else Statement
Python's if-elif-else statement runs a block of code between various possibilities.
Syntax:
if(condition1):
# block of code to be executed if condition1 is true
elif(condition2):
# block of code to be executed if the condition1 is false and condition2 is true
else:
# block of code to be executed if the condition1 is false and condition2 is false
Example:
number = 10
if (number > 15):
print("Number is greater than 15")
elif (number > 10):
print("Number is greater than 10 but less than or equal to 15")
else:
print("Number is equal to 10")
Output:
x is equal to 10