Search code examples
pythonnestedconditional-statements

Using Nested Conditional Expressions


I have an exercise from a book with this code snippet:

def binomial_coeff(n, k):
    """Compute the binomial coefficient "n choose k".

    n: number of trials
    k: number of successes

    returns: int
    """
    if k == 0:
        return 1
    if n == 0:
        return 0

    res = binomial_coeff(n-1, k) + binomial_coeff(n-1, k-1)
    return res

the goal of the exercise is to rewrite the if statements as nested conditional expressions. I understand how to write a conditional expression e.g.

return 1 if k == 0

What am I missing here? By doing this nested, I can't seem to figure it out. PyCharm keeps complaining about that it the second part of the code is unreachable.

return 1 if k == 0 else return 0 if n == 0

Solution

  • return 1 if k == 0 else (0 if n == 0 else binomial_coeff(n-1, k) + binomial_coeff(n-1, k-1))
    

    but seriously: why would you want to do that? That's insanely unreadable.