Python if elif else
The if Statement
The if statement tells a program to run a block of code only if a particular logical conditional test evaluates to true.
Example
x = 50
y = 70
if(x > y):
print("x is greater than y")
if(x < y):
print("y is greater than x")
if(x == 50):
print("x is equal to 50")
if(x != 20):
print("x is not equal to 20")
Output
y is greater than x
x is equal to 50
x is not equal to 20
x is equal to 50
x is not equal to 20
The elif Statement
The elif statement allows a program to check for multiple logical conditional test and runs one block of code only if the test returns True. The elif statement is optional and is similar to the else if statement of other programming languages.
Example
x = 20
y = 10
if(x > y):
print("x is greater than y")
elif(x < y):
print("y is greater than x")
elif(x == 50):
print("x is equal to 50")
elif(x != 20):
print("x is not equal to 20")
Output
x is greater than y
The else Statement
The else statement tells a program to run a block of code if none of the conditional test returns True. The else statement is optional.
Example
x = 40
y = 30
if(x < y):
print("x is greater than y")
elif(x == 50):
print("x is equal to 50")
elif(x != 40):
print("x is not equal to 20")
else:
print("None of the test is true")
Output
None of the test is true