A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/one-liner-for-python-if-elif-else-statements/ below:

Python If Else in One Line

Python If Else in One Line

Last Updated : 18 Dec, 2024

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)  

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)  

Explanation:

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)  

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4