Python - one if-elif-else expression

I am trying to condense the if-elif-else statement on one line. I tried:

a == 1 ? print "one" : a == 2 ? print "two" : print "none" 

But I got a syntax error. I also tried:

 print "one" if a == 1 else print "two" if a == 2 else print "none" 

But I also got a syntax error.

What can I do to make any of these answers better or create a working answer?

+6
source share
7 answers

Try:

 print {1: 'one', 2: 'two'}.get(a, 'none') 
+14
source

Python terminal operator is a form expression

 X if Y else Z 

where X and Z are values, and Y is a Boolean expression. Try the following:

 print "one" if a==1 else "two" if a==2 else "none" 

Here, the value of the expression "two" if a==2 else "none" is the value returned first when a==1 is false. (It is parsed as "one" if a == 1 else ( "two" if a==2 else "none") .) It returns one of "one" , "two" or "none" , which is then passed as the only one argument to the print statement.

+8
source

Use nested conditional expressions (ternary operator):

 >>> a = 2 >>> print 'one' if a == 1 else 'two' if a == 2 else 'none' two 
+4
source

I would use dict instead of nested if

 options = {1: "one", 2: "two"} print options.get(a, 'none') 
+4
source

Use tuple index and conditional:

 print ('one', 'two', 'none')[0 if a==1 else 1 if a==2 else 2] 

Alternatively, if the relation to the index can be an expression:

 print ('one', 'two', 'none')[a-1 if a in (1,2) else -1] 

You can also combine the tuple index method with dict to get the index, to get something more readable than the direct approach (IMHO):

 print ('one', 'two', 'none')[{1:0,2:1}.get(a, -1)] 
+2
source
 print "one" if a == 1 else "two" if a == 2 else "none" 
0
source
 print "one" if a == 1 else("two" if a ==2 else "None") 
0
source

All Articles