covfefe
covfefe

Reputation: 2675

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.

Upvotes: 1

Views: 2689

Answers (4)

Ohad Eytan
Ohad Eytan

Reputation: 8464

You have 2 options:

  1. Use the if/else statement:

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

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

each has different syntax and meaning

Upvotes: 7

chapelo
chapelo

Reputation: 2562

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

def sum_double(a, b): return ((a==b) + 1) * (a+b)

Or using lambda,

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

Upvotes: 0

Karin
Karin

Reputation: 8610

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

Upvotes: 8

snakile
snakile

Reputation: 54521

You should delete the second return.

def sum_double(a, b):
    return 2*(a+b) if a == 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.

Upvotes: 4

Related Questions