Inline conditionally between more than two values

I need to do something like this:

if A function(a) elif B function(b) else function(c) 

I found a simpler version here:

 function(a if A else c) 

Is there a version for elif ? Something like:

 function(a if A b elif B else c) 

How do I write this (if it exists)? The above code does not look right.

+7
python if-statement
source share
1 answer

No, no elif s. Just connect if s:

 function(a if A else b if B else c) 

Which is equivalent (like precedence from left to right):

 function(a if A else (b if B else c)) 

Obviously this can get complicated (and over the PEP8 limit of 80 char), EG:

 move(N if direction == "N" else E if direction == "E" else S if direction == "S" else W) 

In this case, a longer form is better:

 if direction == "N": move(N) elif direction == "E": move(E) elif direction == "S": move(S) else: move(W) 
+8
source share

All Articles