Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

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

Answer*

Draft saved
Draft discarded
Cancel
2
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. Commented Nov 4, 2021 at 8:58
  • 1
    Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. Commented Nov 4, 2021 at 16:49

lang-py

AltStyle によって変換されたページ (->オリジナル) /