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.
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.
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.”