Python elif Statement
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

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

x is smaller than y

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

Second Class

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

Adult category

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

Exit

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 !