Every day we make decisions. When I get up in the morning, I need my shake. Now, for the shake, I need 500 ml Milk, 100 gms of Oats, 1 Banana, 1 Kiwi, and 1 Apple. In case, I don’t have any one of these, it can spell trouble. What’s the trouble ? I cannot make my shake.
In programming, we have a similar structure to situations such as these. Decision making is done with a set of statements called if, else-if, and else.
If: If a certain condition is met, we perform a block of code.
Else-if: If the IF condition is not met, we perform the code written in else-if
Else: If the IF condition, and the ELSE-IF condition are both not met, we perform this block of code.
Sr.No. | Statement & Description |
---|---|
1 | An if statement consists of a boolean expression followed by one or more statements. |
2 | An elif statement is python’s way of saying “if the previous conditions were not true, then try this condition”. |
3 | The else keyword catches anything which isn’t caught by the preceding conditions. |
A more picturesque, and descriptive version can be seen in this image below:
IF statement
Example:
x = 33
y = 200
if y > x:
print(“y is greater than x”)
Output:
y is greater than x
Please note the indentation. In Python, we use indentations as a way of saying that the code which follows the statement is enclosed. In other programming languages, we tend to use braces, or a parenthesis for the same. In python, things are slightly simpler, and we use indentations.
ELIF statement
Example:
x = 56
y = 56
if x > y:
print(“x is greater than y”)
elif x == y:
print(“x and y are equal”)
Output:
x and y are equal
From the above example, we can see that because a and b both have equal values, the first block was not satisfied. Instead, the second block of code under elif, has been executed.
ELSE statement
Example:
x = 100
y = 50
if x > y:
print(“x is greater than y”)
elif x == y:
print(“x and y are equal”)
else:
print(“x is greater than y”)
Output:
x is greater than y