Python elif Statement
Understanding the elif Keyword
In Python, the
elif keyword
stands for “else if”. It is used when you want to check multiple conditions
one after another.
-
If the first
ifcondition fails, Python moves to theelifcondition. - As soon as one condition evaluates to True, its block of code runs, and the remaining conditions are ignored.
Basic Example of elif
Example: Comparing Two Numbers
Explanation:
-
The
ifcondition checks whetherxis greater thany. -
Since it is false, Python evaluates the
elifcondition. -
The
elifcondition is true, so the message is printed.
Using Multiple elif Conditions
You can include any number of
elif
statements in a decision-making structure. Python checks each condition in
sequence and executes the first one that matches.
Example: Student Result Evaluation
Output Explanation: The program evaluates conditions from
top to bottom. Since
marks is 68,
the "Second Class" message is printed.
How elif Execution Works
Python follows these rules when using
elif:
- Conditions are checked from top to bottom
- Only one block of code is executed
- Once a condition is true, the rest are skipped
Even if multiple conditions could be true, only the first true condition runs.
Example: Age-Based Classification
Why
else is
useful:
It catches all remaining cases and ensures the program always produces
output.
When Should You Use elif?
Use
elif when:
- Conditions are mutually exclusive
- Only one outcome should be executed
- You want cleaner and more efficient logic
Using multiple
if statements
instead of
elif can
cause unnecessary checks.
Example: Menu Selection Program
Explanation: Only one menu option is executed. Python stops checking after a match is found.
