Search code examples
pythonpython-3.xreturnsyntax-error

Python can the line "return x if y" be used?


In this answer it is stated that you can use return A+1 if A > B else A-1in python 3, yet when i try to use it:

def max3(a,b,c):
    return a if a > b and c
    return b if b > c else c

i get an invalid syntax error. I've tried looking online but I can't find anything on this, if anyone could help I'd appreciate it.

thanks.


Solution

  • You can nest the conditional expression:

    def max3(a,b,c):
        return a if a > b and a > c else b if b > c else c
    

    Just make sure to always have an else part, otherwise the expression won't know what to evaluate to. Whether this is the most readable solution is at best questionable. There is no price for fewest lines/bytes (unless you are playing code golf).

    Also note that a > b and c is not the same as a > b and a > c. You can shorten that to b < a > c, but then readability will take another hit.