Table of contents
1.
Introduction
2.
Python shorthand if else:
2.1.
Python
3.
Syntax of if elif else statement
3.1.
Python
4.
One liner if elif else statements
4.1.
Python
5.
Syntax of Python one liner if elif else statement:The syntax for a one-liner if-elif-else statement in Python is 
5.1.
Python
6.
Frequently Asked Questions
6.1.
Can you have multiple elif statements in an if-elif-else statement?
6.2.
Is the else statement required in an if-elif-else statement?
6.3.
Can you nest if-elif-else statements inside each other?
7.
Conclusion
Last Updated: Jul 25, 2024
Easy

Elif Statement in Python

Author Pallavi singh
0 upvote

Introduction

If statements are a fundamental concept in programming that allow you to control the flow of your code based on certain conditions. In Python, the elif statement is an extension of the if statement that lets you check for multiple conditions. It's a powerful tool that can help you write more efficient and readable code. 

Elif Statement in Python

In this article, we'll discuss the syntax and usage of the elif statement in Python, along with some examples to help you understand how it works.

Python shorthand if else:

In Python, you can write if-else statements in a more concise way using the ternary operator. This is also known as the conditional expression or the inline if-else statement. The syntax for the shorthand if-else statement is:

value_if_true if condition else value_if_false


For example : 

  • Python

Python

age = 20

is_adult = "Yes" if age >= 18 else "No"

print(is_adult) 
You can also try this code with Online Python Compiler
Run Code


Output: 

Yes


In this example, we have a variable `age` with a value of 20. We use the ternary operator to assign the value "Yes" to the variable `is_adult` if `age` is greater than or equal to 18, and "No" otherwise. The resulting value is then printed, which outputs "Yes" since 20 is indeed greater than or equal to 18.

The shorthand if-else statement is a convenient way to write simple conditional assignments in a single line of code. It can make your code more readable and concise, especially when you have short and straightforward conditions.

Syntax of if elif else statement

The syntax of the if-elif-else statement in Python is :

if condition1:
    # code block 1
elif condition2:
    # code block 2
elif condition3:
    # code block 3
else:
    # code block 4


Let's discuss each part of the syntax:
 

1. The `if` keyword is followed by a condition (`condition1`). If this condition evaluates to `True`, the code block indented under the `if` statement (`code block 1`) is executed.
 

2. If `condition1` is `False`, the program moves to the next `elif` statement. The `elif` keyword is followed by another condition (`condition2`). If this condition is `True`, the code block indented under the `elif` statement (`code block 2`) is executed.
 

3. You can have multiple `elif` statements to check for additional conditions. If the previous conditions are `False`, the program moves to the next `elif` statement and evaluates its condition (`condition3`). If it's `True`, the corresponding code block (`code block 3`) is executed.
 

4. If none of the conditions in the `if` and `elif` statements are `True`, the code block under the `else` statement (`code block 4`) is executed. The `else` statement is optional and can be omitted if you don't need a default case.


Let’s look at an example that shows the usage of the if-elif-else statement:

  • Python

Python

def get_grade(score):

   if score >= 90:

       return "A"

   elif score >= 80:

       return "B"

   elif score >= 70:

       return "C"

   elif score >= 60:

       return "D"

   else:

       return "F"

score = 85

grade = get_grade(score)

print(f"Your grade is: {grade}") 
You can also try this code with Online Python Compiler
Run Code


Output: 

Your grade is: B


In this example, we have a function `get_grade()` that takes a `score` as input and returns the corresponding grade based on the score. The if-elif-else statement is used to check the score against different ranges and return the appropriate grade.

We call the `get_grade()` function with a score of 85, and it returns the grade "B" since the score is greater than or equal to 80 but less than 90.

One liner if elif else statements

In Python, you can write if-elif-else statements in a single line using the ternary operator, similar to the shorthand if-else statement we discussed earlier. This can be useful for simple conditional assignments or expressions.

The syntax for a one-liner if-elif-else statement is:

value_if_condition1 if condition1 else value_if_condition2 if condition2 else value_if_condition3


Let's discuss this syntax:

- If `condition1` is `True`, the expression evaluates to `value_if_condition1`.
 

- If `condition1` is `False`, it moves to the next part: `value_if_condition2 if condition2 else value_if_condition3`.
 

  - If `condition2` is `True`, the expression evaluates to `value_if_condition2`.
 

  - If `condition2` is `False`, the expression evaluates to `value_if_condition3`.
 

Here's an example to show the usage of a one-liner if-elif-else statement:

  • Python

Python

def get_grade(score):

   return "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "D" if score >= 60 else "F"

score = 85

grade = get_grade(score)

print(f"Your grade is: {grade}")
You can also try this code with Online Python Compiler
Run Code


Output: 

Your grade is: B


In this example, we have the same `get_grade()` function as before, but this time, we use a one-liner if-elif-else statement to determine the grade based on the score. The conditions are evaluated from left to right, and the first condition that evaluates to `True` determines the returned value.

When we call the `get_grade()` function with a score of 85, it evaluates the conditions and returns "B" since the score is greater than or equal to 80 but less than 90.

One-liner if-elif-else statements can make your code more concise, but it's important to use them judiciously. If the conditions become too complex or the line becomes too long, it can reduce code readability. In such cases, it's often better to use a regular if-elif-else statement for clarity.

Syntax of Python one liner if elif else statement:
The syntax for a one-liner if-elif-else statement in Python is 

result = value_if_condition1 if condition1 else value_if_condition2 if condition2 else value_if_condition3 if condition3 else default_value


Let's discuss the components of this syntax:

- `result`: This is the variable that will store the value determined by the if-elif-else conditions.
 

- `value_if_condition1`, `value_if_condition2`, `value_if_condition3`: These are the values that will be assigned to `result` if the corresponding condition evaluates to `True`.
 

- `condition1`, `condition2`, `condition3`: These are the conditions that are evaluated in order. The first condition that evaluates to `True` determines the value assigned to `result`.
 

- `default_value`: This is the value that will be assigned to `result` if none of the conditions evaluate to `True`. It acts as the `else` case.


Let’s look at an example that shows the usage of the one-liner if-elif-else statement syntax:

  • Python

Python

def get_day_type(day):

   return "Weekend" if day in ["Saturday", "Sunday"] else "Weekday" if day in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] else "Invalid day"

day = "Monday"

day_type = get_day_type(day)

print(f"{day} is a {day_type}") 

day = "Sunday"

day_type = get_day_type(day)

print(f"{day} is a {day_type}")

day = "InvalidDay"

day_type = get_day_type(day)

print(f"{day} is an {day_type}")
You can also try this code with Online Python Compiler
Run Code

 

Output: 

Monday is a Weekday
Sunday is a Weekend
InvalidDay is an Invalid day


In this example, we have a function `get_day_type()` that takes a `day` as input and returns the type of day using a one-liner if-elif-else statement. The conditions check if the day is in the list of weekdays or weekend days, and the corresponding value is returned. If the day is not valid, the default value "Invalid day" is returned.

We call the `get_day_type()` function with different days and print the results. The one-liner if-elif-else statement allows us to determine the day type concisely based on the conditions.

Remember that while one-liner if-elif-else statements can be useful for simple cases, they can become harder to read if the conditions or values are complex. Use them judiciously and prioritize code readability.

Frequently Asked Questions

Can you have multiple elif statements in an if-elif-else statement?

Yes, you can have multiple elif statements to check for different conditions. The elif statements are evaluated in order until a condition is True or the else block is reached.

Is the else statement required in an if-elif-else statement?

No, the else statement is optional. You can omit it if you don't need a default case to handle when none of the conditions in the if and elif statements are True.

Can you nest if-elif-else statements inside each other?

Yes, you can nest if-elif-else statements inside each other to create more complex decision-making structures. This allows you to handle different conditions and execute specific code blocks based on multiple criteria.

Conclusion

In this article, we have learned about the elif statement in Python, which is an extension of the if statement that allows you to check for multiple conditions. We discussed the syntax and usage of if-elif-else statements, including the shorthand and one-liner versions. We also provided practical examples to show how these statements can be used to control the flow of your code based on different conditions.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass