Python elif Statement

Python elif Statement

Kishore V


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 if condition fails, Python moves to the elif condition.

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

Try it Yourself

Explanation:

    • The if condition checks whether x is greater than y.

    • Since it is false, Python evaluates the elif condition.

    • The elif condition 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

Try it Yourself

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:

    1. Conditions are checked from top to bottom

    2. Only one block of code is executed

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

Try it Yourself

Why else is useful:

    • It catches all remaining cases

    • 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

Try it Yourself

Explanation:

Only one menu option is executed

Python stops checking after a match is found


Our website uses cookies to enhance your experience. Learn More
Accept !