Else and Elif Statement
Elif Statement
The elif
keyword allows you to check multiple expressions for True
and execute a block of code as soon as one of the conditions is true.
Example:
python
1a = 33
2b = 33
3if b > a:
4 print("b is greater than a")
5elif a == b:
6 print("a and b are equal")
In this example, since a
and b
are equal, the output will be:
1a and b are equal
Else Statement
The else
keyword is used to catch anything that isn't caught by the preceding conditions.
Example:
python
1a = 200
2b = 33
3if b > a:
4 print("b is greater than a")
5elif a == b:
6 print("a and b are equal")
7else:
8 print("a is greater than b")
Here, since a
is greater than b
, the output will be:
1a is greater than b
Else Without Elif
You can have an else
statement without an elif
.
Example:
python
1a = 200
2b = 33
3if b > a:
4 print("b is greater than a")
5else:
6 print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can write it on the same line as the if
statement.
Example:
python
1if a > b: print("a is greater than b")
Short Hand If ... Else
For simple conditions with one statement for if
and one for else
, you can write it all on the same line using a ternary operator.
Example:
python
1a = 2
2b = 330
3print("A") if a > b else print("B")
Logical Operators
1. And
The and
keyword is used to combine conditional statements.
Example:
python
1a = 200
2b = 33
3c = 500
4if a > b and c > a:
5 print("Both conditions are True")
2. Or
The or
keyword is used to check if at least one of the conditions is true.
Example:
python
1if a > b or a > c:
2 print("At least one of the conditions is True")
3. Not
The not
keyword reverses the result of the conditional statement.
Example:
python
1if not a > b:
2 print("a is NOT greater than b")