Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

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

defsum_double(a, b):
  return2*(a+b) if (a == b) else a+b

Solution 2:

You have 2 options:

  1. Use the if/else statement:

    def sum_double(a, b):
        if (a == b):                                 #if/else statement
            return2*(a+b) # <--- return statement   #^
        else:                                        #^
            return a+b     # <--- return statement   #^
    
  2. Use the if/else conditional expression:

    defsum_double(a, b):
        return2*(a+b) if (a == b) else a+b
    #         (^                          ^)  <--- conditional expression #  (^                                 ^)  <--- return statement

each has different syntax and meaning

Solution 3:

You should delete the second return.

def sum_double(a, b):
    return2*(a+b) ifa== b else a+b

The value of the 2*(a+b) if a == b else a+b expression is what you actually want to return.

Solution 4:

In Python, True, False are the same as 1, 0:

defsum_double(a, b): return ((a==b) + 1) * (a+b)

Or using lambda,

sum_double = lambda a, b: ((a==b) + 1) * (a+b)

Post a Comment for "Python One-liner If Else Statement"