Putting if-elif-else statement on one line?

I read the links below, but that does not concern my question.
Does Python have a ternary conditional operator? (we are talking about compressing the if-else statement on one line)

Is there an easier way to write an if-elif-else statement so that it matches a single line?
For example,

if expression1: statement1 elif expression2: statement2 else: statement3 

[UPDATE]

 if i>100: x=2 elif i<100: x=1 else: x=0 

I just feel that the example described above can be written as follows: it may look more concise.

 x=2 if i>100 elif i<100 1 else 0 [WRONG] 
+95
python syntax
Dec 25
source share
12 answers

No, this is impossible (at least not with arbitrary statements), and this is not desirable. Placing everything on one line is likely to violate PEP-8 , which states that lines should not exceed 80 characters.

This is also against Zen Python: "Reading is calculated." (Type import this at the Python prompt to read all of this).

You can use ternary expression in Python, but only for expressions, not for operators:

 >>> a = "Hello" if foo() else "Goodbye" 

Edit:

Now your revised question shows that the three statements are identical except for the assigned value. In this case, the chain ternary operator really works, but I still think it is less readable:

 >>> i=100 >>> a = 1 if i<100 else 2 if i>100 else 0 >>> a 0 >>> i=101 >>> a = 1 if i<100 else 2 if i>100 else 0 >>> a 2 >>> i=99 >>> a = 1 if i<100 else 2 if i>100 else 0 >>> a 1 
+145
Dec 25 '12 at 9:16
source share

If you only need different expressions for different cases, this might work for you:

 expr1 if condition1 else expr2 if condition2 else expr 

For example:

 a = "neg" if b<0 else "pos" if b>0 else "zero" 
+48
Dec 25
source share

Just insert another if clause in the else statement. But that does not make him more beautiful.

 >>> x=5 >>> x if x>0 else ("zero" if x==0 else "invalid value") 5 >>> x = 0 >>> x if x>0 else ("zero" if x==0 else "invalid value") 'zero' >>> x = -1 >>> x if x>0 else ("zero" if x==0 else "invalid value") 'invalid value' 
+14
Dec 25 2018-12-12T00: 00Z
source share

Optionally, you can actually use the get method from dict :

 x = {i<100: -1, -10<=i<=10: 0, i>100: 1}.get(True, 2) 

You do not need a get method if one of the keys is guaranteed to evaluate to True :

 x = {i<0: -1, i==0: 0, i>0: 1}[True] 

The maximum of one of the keys should ideally be True . If more than one key evaluates to True , the results may seem unpredictable.

+5
Nov 22 '16 at 13:50
source share

There is an alternative which, in my opinion, is unreadable, but I will share as much as curiosity:

 x = (i>100 and 2) or (i<100 and 1) or 0 

Further information here: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not

+4
Jan 26 '16 at 16:44
source share
 if i > 100: x = 2 elif i < 100: x = 1 else: x = 0 

If you want to use the above code on a single line, you can use the following:

 x = 2 if i > 100 else 1 if i < 100 else 0 

In this case, x will be assigned 2 if i> 100, 1 if i <100, and 0 if i = 100.

+4
Jan 10 '19 at 3:24
source share

It also depends on the nature of your expressions. The general advice on the other β€œdo not do this” answers is quite applicable to general expressions and general expressions.

But if you need a "dispacth" table, for example, calling another function depending on the value of this option, you can put the functions in the dictionary.

Something like:

 def save(): ... def edit(): ... options = {"save": save, "edit": edit, "remove": lambda : "Not Implemented"} option = get_input() result = options[option]() 

(which instead

 if option=="save": save() ... 

)

+2
Dec 25 '12 at 12:55
source share

People have already mentioned ternary expressions. Sometimes with a simple conditional assignment, as an example, you can use a mathematical expression to perform conditional assignment. This may not make your code very readable, but it gets on one fairly short line. Your example can be written as follows:

 x = 2*(i>100) | 1*(i<100) 

The comparison will be True or False, and when multiplying numbers it will be 1 or 0. You can use + instead of \ in the middle.

+2
Dec 25 '12 at 21:30
source share

The ternary operator is the best way to summarize. Syntax: variable = value_1 if condition else value_2 . So, for your example, you have to apply the ternary operator twice:

 i = 23 # set any value for i x = 2 if i > 100 else 1 if i < 100 else 0 
+1
May 17 '19 at 21:14
source share

You can use nested ternary if statements.

 # if-else ternary construct country_code = 'USA' is_USA = True if country_code == 'USA' else False print('is_USA:', is_USA) # if-elif-else ternary construct # Create function to avoid repeating code. def get_age_category_name(age): age_category_name = 'Young' if age <= 40 else ('Middle Aged' if age > 40 and age <= 65 else 'Senior') return age_category_name print(get_age_category_name(25)) print(get_age_category_name(50)) print(get_age_category_name(75)) 
0
Mar 31 '18 at 20:31
source share

Generally not. However, if the entire contents of if-elif-else is an expression, it can be written on the same line using ternary operators, which corresponds to the syntax expr1 if cond1 else expr2 . By chaining them together, you can compress if-elif-else as follows:

x = 1 if i>0 (else 1 if i<0 else 0)

Typically, the standard if-elif-else is considered a better style and more readable than chain ternary operators.

0
May 24 '19 at 19:16
source share
 firstNumber = float(input("What is your first number?")) secondNumber = float(input("What is your second number?")) if (firstNumber / secondNumber) : print("The result is:" + str(float(firstNumber / secondNumber))) elif (firstNumber / secondNumber) : print("" + str(float(firtNumber / secondNumber) + " ==" + "0")) else : print("Zero is not allowed in Math.") 
-2
Jul 17 '19 at 4:12
source share



All Articles