In Python, if-else statements are used to execute a piece of code if a condition is true or not.
The if
keyword is generally used with a
comparison operator (==
, !=
, >
, ≥
,
<
, and ≤
). These comparison operators in Python
are the same as those in mathematics.
For example;
a = 34
b = 76
if a > b:
print(a, "is greater than", b)
else:
print(a, "is not greater than", b)
The output-
34 is not greater than 76 .
In the example given above, the interpreter checks if the value of the
variable a
is greater than that of variable b
. If it
is, the output is given as {a} is greater than {b}
.
However, if the value of a
is lesser than or equal to
b
(as in the example above), the output is
{a} is not greater than {b}
.
In some cases,
identity and membership operators
(is
, is not
and in
,
not in
respectively) are also used.
Elif Statement
The elif statement is used when you want a specific output for a condition other than the one given in the if statement. In other words, it is used to give different outputs for multiple conditions.
For example-
a=26
b=52
if a>b:
print(a, "is greater than", b)
elif a==b:
print(a, "is equal to", b)
else:
print(a, "is lesser than", b)
The output-
26 is lesser than 52
In this example, the if statement works as in the previous example. In the next line, however, the interpreter checks if the value of ‘a’ is the same as ‘b’. If it is, it prints “{a} is equal to {b}”.The else statement is again, executed as usual.
Indentations
Indentations are the blank whitespaces that are present in the beginning of each line of code.
Python relies heavily on indentations, unlike languages like C, C++, Javascript, etc, which use curly brackets “{}”, for defining if the statement or variable is inside a loop, a specific part of code, or just in the main body.
This is called scope. (More about it in a future post.)
So, if you forget to add indentations where they are supposed to be, or add extra indentations, you will get an error.
For example-
a = 50
if a > 45:
print(a, "> 45.")
This will raise an error.
Nested if statements
You can add if
statements inside other if
statements
too! Such statements are called nested if statements.
For example-
a=45
if a>10:
print(a, "is greater than 10.")
if a>40:
print(a, "is also greater than 40.")
else:
print(a, "is not greater than 40, though.")
else:
print(a, "is lesser than 10.")
The output-
45 is greater than 10.
45 is also greater than 40.
In this example, the nested if statement gets executed only if the first
condition (here, a>10
) is true. If not, it remains unused.
That is all for the basics of conditional statements in Python.
Happy Coding,
Aarav Iyer