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
1
2
3
4
5
6
a = 33
b = 33
if b > a:
    print("b is greater than a")
elif a == b:
    print("a and b are equal")

In this example, since a and b are equal, the output will be:

1
a and b are equal

Else Statement

The else keyword is used to catch anything that isn't caught by the preceding conditions.

Example:

python
1
2
3
4
5
6
7
8
a = 200
b = 33
if b > a:
    print("b is greater than a")
elif a == b:
    print("a and b are equal")
else:
    print("a is greater than b")

Here, since a is greater than b, the output will be:

1
a is greater than b

Else Without Elif

You can have an else statement without an elif.

Example:

python
1
2
3
4
5
6
a = 200
b = 33
if b > a:
    print("b is greater than a")
else:
    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
1
if 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
1
2
3
a = 2
b = 330
print("A") if a > b else print("B")

Logical Operators

1. And

The and keyword is used to combine conditional statements.

Example:

python
1
2
3
4
5
a = 200
b = 33
c = 500
if a > b and c > a:
    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
1
2
if a > b or a > c:
    print("At least one of the conditions is True")

3. Not

The not keyword reverses the result of the conditional statement.

Example:

python
1
2
if not a > b:
    print("a is NOT greater than b")

Frequently Asked Questions