0

I have the following Code in Python:

def show_sequence(n):
    if n > 0:
        return "+".join((str(i) for i in range(n+1))) + " = %d" %(sum(range(n+1)))
    elif n == 0:
        return "0=0"
    else:
        return str(n) + "<0"

Question: Is there a syntax correct way of putting all lines into one return statement if there are 3 if-statements? I know it works with one if- & else-statement but im a fan of one-liner and already asked this myself several times.

Jero
  • 47
  • 4
  • 8
    Only if you wanted one absurdly long and hard to read line instead of code that makes sense. – khelwood Jul 09 '20 at 18:45
  • I know, this is a bad example for clear coding but I could not figure out, how the syntax should look like. Already tried by using "or" but it did not work – Jero Jul 09 '20 at 18:47
  • 1
    `return "+".join(...) if n > 0 else "0=0" if n == 0 else str(n) + "<0"`. (But if anyone else has to read your code, please don't inflict this kind of syntax abuse on them). – ekhumoro Jul 09 '20 at 18:53
  • https://rpo.library.utoronto.ca/poems/there-was-young-bard-japan – alani Jul 09 '20 at 18:55
  • 1
    I wouldn't put everything on one line, but you also can easily generalize `n > 0` and `n == 0` into a single `n >= 0` case, as `"+".join([0]) == "0"` and `sum([0]) == 0`. – chepner Jul 09 '20 at 19:00
  • There's little more work involved in folding `n < 0` in there. `range(min(0,n),n+1)` will generate `[-n]` when `n` is negative, and `sum(range(-3)) == 0`, as the range is empty. – chepner Jul 09 '20 at 19:06

2 Answers2

2

Inline if-statements can be chained like this:

"a" if 0 else "b" if 0 else "c"

(replace the 0s with 1s to see the return value change)

Simon Crane
  • 2,122
  • 2
  • 10
  • 21
0

You can use this:

result = True if a==b else False
fro
  • 402
  • 3
  • 8