1

Can an if-else expression be the argument of 'return'?

Here's an example of what I'm trying to do:

return m +
    if a:
        x
    elif b:
        y
    else c:
        z

I could write as:

addend = m
if a:
        m += x
    elif b:
        m += y
    else c:
        m += z
return m
6
  • Have you tried writing a function using the return form you are asking about? Please share that function. When you ran that code what result did you get? If you don't understand the outcome please share it with us. Commented Aug 17, 2015 at 4:13
  • def rental_car_costs(days): return days*40 + if days>=7: (-50) elif days>=3: (-20) gives me: syntax error: invalid syntax Commented Aug 17, 2015 at 4:28
  • So the system did tell you that you could not do what you were doing. It told you that it was a syntax error. If you didn't understand the syntax error then posting the code and asking for help resolving that syntax error and/or asking for a better option would be a better way to ask your question. Not trying to be nasty, just trying to help you get the best out of SO. Check the answer from paxdiablo for some better ways to do what you are trying to do and to resolve other problems in your code. Commented Aug 17, 2015 at 4:35
  • I appreciate your feedback on how I formulated the question. Is there room on SO for general questions on how to combine elements in python? I know in LISP, you could certainly plug the output of a conditional into the equivalent of 'return'. My question here is meant to be: can the same be done with python? Commented Aug 17, 2015 at 4:42
  • Actually, if I'm being honest, I find your comment condescending and disingenuous. The question I asked is what I want to find out - there's no other, hidden, implicit issue behind the question that I'm trying to make you guess. I was not looking for a better option, for example. I really did want to know how if-else could be combined with return. I'm optimistic that your response is not typical of this community. Commented Aug 17, 2015 at 18:45

1 Answer 1

3

Well, you can use Python's ternary method, such as:

return m + (x if a else y if b else z)

But it may be more readable to just do something like:

if a: return m + x
if b: return m + y
return       m + z

As an aside, else c: is not really sensible code: you use if/elif if you have a condition, or else for default action (no condition).


For example, in terms of the code you posted in a comment, you could opt for the succinct, yet still self-documenting:

def rental_car_costs(days):
    basecost = days * 40
    discount = 50 if days >= 7 else 20 if days >= 3 else 0
    return basecost - discount
Sign up to request clarification or add additional context in comments.

Comments