Friday, November 21, 2025
HomeLanguagesOne Liner for Python if-elif-else Statements

One Liner for Python if-elif-else Statements

If-elif-else statement is used in Python for decision-making i.e the program will evaluate test expression and will execute the remaining statements only if the given test expression turns out to be true. This allows validation for multiple expressions.

Syntax :

if test expression:
    Body of if
    
elif test expression:
    Body of elif
    
else: 
    Body of else

The concept can be implemented using the short-hand method using ternary operation.

One Liner for Python if-elif-else Statements

Syntax:

{(condition1 :  <code1>) , (condition2 :  <code2>) }.get(True, <code3>)

This can be easily interpreted as if condition 1 is true run code 1 if condition 2 is true run code 2 and if both of them are false run the third code.

Example:

Python3




x = 87
  
result = {x > 190: "First condition satisfied!", 
          x == 87: "Second condition satisfied!"}.get(
  True, "Third condition satisfied")
  
print(result)


Output:

Second condition satisfied!

Disclaimer: the below code won’t get you the desired results for this syntax of if-elif-else in Python:

Python3




x = 87
  
{x > 190: print("First condition satisfied!"),
 x == 87: print("Second condition satisfied!")}.get(
  True, print("Third condition satisfied!"))


Output:

First condition satisfied!
Second condition satisfied!
Third condition satisfied!
RELATED ARTICLES

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6781 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11995 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7166 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS