Loading...

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
6 lines
|
25/ 500 tokens
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")
Code Tools

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

text
1 lines
|
5/ 500 tokens
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
8 lines
|
35/ 500 tokens
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")
Code Tools

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

text
1 lines
|
5/ 500 tokens
1
a is greater than b

Else Without Elif

You can have an else statement without an elif.

Example:

python
6 lines
|
25/ 500 tokens
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")
Code Tools

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 lines
|
10/ 500 tokens
1
if a > b: print("a is greater than b")
Code Tools

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
3 lines
|
13/ 500 tokens
1
2
3
a = 2
b = 330
print("A") if a > b else print("B")
Code Tools

Logical Operators

1. And

The and keyword is used to combine conditional statements.

Example:

python
5 lines
|
20/ 500 tokens
1
2
3
4
5
a = 200
b = 33
c = 500
if a > b and c > a:
    print("Both conditions are True")
Code Tools

2. Or

The or keyword is used to check if at least one of the conditions is true.

Example:

python
2 lines
|
18/ 500 tokens
1
2
if a > b or a > c:
    print("At least one of the conditions is True")
Code Tools

3. Not

The not keyword reverses the result of the conditional statement.

Example:

python
2 lines
|
13/ 500 tokens
1
2
if not a > b:
    print("a is NOT greater than b")
Code Tools