user3004041 user3004041 - 1 year ago 90
Python Question

Python one-liner if else statement

This problem is taken from codingbat. Given two int values, return their sum. Unless the two values are the same, then return double their sum.

I'm trying to solve it in one line:

def sum_double(a, b):
return 2*(a+b) if (a == b) else return a+b


But I'm getting an error and I'm not sure why. Would appreciate any help.

Answer Source

You can't have a return in the else clause. It should be:

def sum_double(a, b):
  return 2*(a+b) if (a == b) else a+b