1

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.

6
  • 8
    Only if you wanted one absurdly long and hard to read line instead of code that makes sense. Commented Jul 9, 2020 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 Commented Jul 9, 2020 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). Commented Jul 9, 2020 at 18:53
  • rpo.library.utoronto.ca/poems/there-was-young-bard-japan Commented Jul 9, 2020 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. Commented Jul 9, 2020 at 19:00

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0

You can use this:

result = True if a==b else False 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.