2

My question is this: is it possible to use full conditional statements (if, elif, else) in a return?

I am aware that I can do this:

def foo():
    return 10 if condition else 9

Am I able to do something like this:

def foo():
    return 10 if condition 8 elif condition else 9

Afterthought: Looking at this form it does not appear to be very readable and my guess is it probably does not have any valid use cases. Regardless, curiosity prompts me to ask. Thank you in advance for any answers.

Daniel
  • 547
  • 5
  • 25

2 Answers2

5

It sure is! Although should be used with caution, unless you're an expert like Peter Norvig (code taken from here)!

def hand_rank(hand):
    "Return a value indicating how high the hand ranks."
    # counts is the count of each rank
    # ranks lists corresponding ranks
    # E.g. '7 T 7 9 7' => counts = (3, 1, 1); ranks = (7, 10, 9)
    groups = group(['--23456789TJQKA'.index(r) for r, s in hand])
    counts, ranks = unzip(groups)
    if ranks == (14, 5, 4, 3, 2):
        ranks = (5, 4, 3, 2, 1)
    straight = len(ranks) == 5 and max(ranks)-min(ranks) == 4
    flush = len(set([s for r, s in hand])) == 1
    return (
        9 if (5, ) == counts else
        8 if straight and flush else
        7 if (4, 1) == counts else
        6 if (3, 2) == counts else
        5 if flush else
        4 if straight else
        3 if (3, 1, 1) == counts else
        2 if (2, 2, 1) == counts else
        1 if (2, 1, 1, 1) == counts else
        0), ranks

To clarify, you simply use else if instead of elif when composing Python "ternary" statements with multiple predicates.

3

You can construct a ternary in the else clause of the outer ternary.

a = 3
b = 2
def foo():
    return 10 if a<b     \
           else 8 if a>b \
           else 9        \

print(foo())
138
  • 554
  • 5
  • 14