Elif in Python

Overview

The elif keyword in Python is an integral part of conditional statements, specifically used in the if-elif-else construct. It stands for "else if" and is used to check multiple conditions in a sequence. When a condition in an if statement evaluates to False, the program can proceed to check additional conditions using elif. This allows for a more streamlined and readable way to handle multiple potential execution paths based on different conditions.

Syntax and Usage

The general form of the if-elif-else construct in Python is as follows:

if condition1:
    body1
elif condition2:
    body2
elif condition3:
    body3
.
.
.
elif condition(n-1):
    body(n-1)
else:
    body(n)

In this structure, the program evaluates each condition in sequence. If condition1 is True, it executes body1. If not, it checks condition2, and so on. If none of the conditions are True, the else block is executed. The body sections are sequences of one or more Python statements, each separated by newlines and at the same level of indentation.

Example: Guessing Game

Consider a simple guessing game where you want to determine if a guess is low, correct, or high compared to a target number:

guess = 4  
target = 7
 
if guess < target:
  print("Low")
elif guess == target:
  print("Correct!")
else:         #A
  print("High")
 
Low
#A if the guess is not low and not equal, it must be high.

In this example, the program checks if the guess is less than the target. If so, it prints "Low". If the guess equals the target, it prints "Correct!". If neither condition is met, it defaults to printing "High".

Optional Clauses

The elif and else clauses are optional. You can have as many elif clauses as needed, or none at all. Similarly, the else clause can be omitted if not required. If no conditions evaluate to True and there is no else clause, the program simply does nothing.

Here's another example demonstrating optional elif and else clauses:

x = 5
if x < 5:
    y = -1
    z = 5
elif x > 5:    #A
    y = 1 
    z = 11     
else:          #A
    y = 0        #B
    z = 10       #B
print(x, y, z)
#A optional elif and else clauses. 
#B Python uses indentation to delimit blocks. 

In this example, the program checks if x is less than 5, greater than 5, or neither. Since x is 5, neither the first if nor the elif condition is True, so the else block is executed, resulting in the output 5 0 10.

Indentation

Python uses indentation to define blocks of code. Unlike some other programming languages, Python does not use explicit delimiters like brackets or braces. Each block consists of one or more statements, all at the same level of indentation. This indentation is crucial for the correct execution of the if-elif-else construct.