elif Statement

The elif, a Python keyword, is a contraction of ’else if’. It’s part of Python’s control flow structures and used in conditional testing. Following an if statement and preceding an optional else statement, the elif stands for additional conditions after the original condition (if) fails to meet.

The Role of elif in Control Flow

The elif statement allows a program to execute different blocks of code depending on various conditions. It is written after an if statement and performs its block of code if its condition is true, and the if condition was false.

1x = 20
2if x < 10:
3    print("Less than 10")
4elif x < 50:
5    print("Between 10 and 50")
6else:
7    print("Greater than 50")

In the script above, the output will be Between 10 and 50, because the elif statement’s condition is true (x is less than 50) and the if condition was false (x is not less than 10).

Using Multiple elif Statements

Python allows for multiple elif statements within a single control flow block. Each elif condition is checked in order, until a true condition is encountered, or by reaching the else statement.

1age = 25
2if age < 13:
3    print("Child")
4elif age < 20:
5    print("Teenager")
6elif age < 30:
7    print("Young Adult")
8else:
9    print("Adult")

In the script above, Young Adult will print because the age fits into the third category (less than 30 but more than 20), and this is the first true condition encountered.

Remember

The elif keyword is Python’s way of saying “if the previous conditions were not true, then try this condition.”