If Else Statements

else - to execute code block if condition is not met.

elif - to check alternative condition if the main one is False.

Syntax

else

else if

Else Example

Let's look at a program that checks whether speed is above or below the speed limit for cities (50 km/h).

Output:

Since the condition at line 3 is False, the code inside else block executes.

Elif Example

Let's have a program that categorizes a person depending on his/her height.

Rules are the following:

  • below 160cm - short
  • between 160cm to 185 cm - medium
  • above 185 cm - tall

Output:

Since the condition at line 3 is False and the condition at line 6 is True, the code inside elif block executes.