## else Statements

An else statement follows an if statement, and contains code that is called when the if statement evaluates to False.
As with if statements, the code inside the block should be indented.

x = 4
if x == 5:
print(“Yes”)
else:
print(“No”

Result:

>>
No
>>>

## else Statements

You can chain if and else statements to determine which option in a series of possibilities is true.
For example:

num = 7
if num == 5:
print(“Number is 5”)
else:
if num == 11:
print(“Number is 11”)
else:
if num == 7:
print(“Number is 7”)
else:
print(“Number isn’t 5, 11 or 7”

Result:

>>>
Number is 7
>>>

## elif Statements

The elif (short for else if) statement is a shortcut to use when chaining if and else statements.
A series of if elif statements can have a final else block, which is called if none of the if or elif expressions is True.
For example:

num = 7
if num == 5:
print(“Number is 5”)
elif num == 11:
print(“Number is 11”)
elif num == 7:
print(“Number is 7”)
else:
print(“Number isn’t 5, 11 or 7”

Result:

>>
Number is 7
>>>

NOTE!
In other programming languages, equivalents to the elif statement have varying names, including else if, elseif or elsif.

 BACK NEXT