Open In App

Python If Else in One Line

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, if-else conditions allow us to control the flow of execution based on certain conditions. While traditional if-else statements are usually written across multiple lines, Python offers a more compact and elegant way to express these conditions on a single line.

Python if-else in One Line

In Python, a typical if-else statement is written in multiple lines. However, Python provides a shorthand way to write conditional expressions, which is known as the ternary operator.

Here’s a simple example to illustrate the concept:

Python
x = 10
y = 5

res = "x is greater" if x > y else "y is greater"
print(res)  

Output
x is greater

In this example, the condition x > y is evaluated. Since it’s True, the string "x is greater" is assigned to the variable result. If the condition had been False, the string "y is greater" would have been assigned instead.

Syntax of one-liner if elif else Statement:

This syntax works by evaluating the condition first. If the condition is True, the expression before the else keyword is executed; if the condition is False, the expression after the else is executed.

value_if_true if condition else value_if_false

Example: Determine if a Number is Positive, Negative, or Zero

Python
n = -5

res = "Positive" if n > 0 else "Negative" if n < 0 else "Zero"

print(res)  

Output
Negative

Explanation:

  • num > 0: The first condition checks if the number is greater than 0. If True, it returns "Positive".
  • num < 0: If the first condition is False, it moves to the next condition. If True, it returns "Negative".
  • else "Zero": If both conditions are False, it returns "Zero" as the default result.

One-Line If-Elif-Else in Python

Python does not directly support a true one-liner for if-elif-else statements like it does for a simple if-else. However, we can emulate this behavior using nested ternary operators.

Using Nested Ternary Operators

To write an if-elif-else condition in one line, we can nest ternary operators in the following format:

value_if_true1 if condition1 else value_if_true2 if condition2 else value_if_false

Example:

Python
x = 15

res = "Greater than 20" if x > 20 else "Greater than 10" if x > 10 else "10 or less"
print(res)  

Output
Greater than 10

Explanation:

  • x > 20 is checked first. If True, it returns "Greater than 20".
  • If not, x > 10 is checked. If True, it returns "Greater than 10".
  • If none of the conditions are True, it falls to the final else value: "10 or less".

Next Article

Similar Reads