Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline conditional between more than 2 values

I need to do something like this:

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

I found here simpler version:

function(a if A else c)

Is there version for elif? Something like:

function(a if A b elif B else c)

How should I write this (if this exists)? The code above doesn't look right.

like image 989
user3895596 Avatar asked Dec 15 '14 21:12

user3895596


1 Answers

No, no elifs. Just chain the ifs:

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

Which is equivalent to (as precedence is left to right):

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

Obviously this could get complicated (and over the PEP8 80 char limit), E.G.:

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

In which case the longer form is better:

if direction == "N":
    move(N)
elif direction == "E":
    move(E)
elif direction == "S":
    move(S)
else:
    move(W)
like image 75
matsjoyce Avatar answered Nov 02 '22 04:11

matsjoyce