Pass functional arguments through ternary operator in Python

Viewed 998

This might be a basic question because I am still learning Python. But let's suppose I want to do something like this,

def add(a, b):
    return a + b

a, b, c, d = 1, 2, 3, 4
sum = add(a, b if b == 2 else c, d)

Basically, I am trying to pass multiple functional args from inside a ternary operator(and I want a similar solution, if possible). This code currently gives the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() takes 2 positional arguments but 3 were given

What else have I tried:

  • add((a, b) if b == 2 else (c, d))
  • add(*(a, b) if b == 2 else *(c, d))
4 Answers
>>> add(*((a, b) if b == 2 else (c, d)))
3

As pointed out in the comments, the fact that you need so many parens to do this is a good sign that this is not a good way to structure this code.

sum_ = add(a, b) if b==2 else add(c, d)

above statement is equivalent to

sum_ = 0
if b==2:
    sum_ = add(a, b)
else:
    sum_ = add(c, d)

if in confusion, it is better to write a full statement, and then try to make it simple and in Turney.

Also, it's recommended, not to use the inbuilt function for the variable name

what about

add(*(a, b) if b == 9 else (c, d))

It is similar to

add(*((a, b) if b == 9 else (c, d)))

the problem is in the fucntion argument ,you declare a fucntion with 2 variable but you pass 3 ,what i inderstand you pass argument to funciton and it return the sum of the argument ,you can do this

def add(*args):
   return sum(args)
a, b, c, d = 1, 2, 3, 4
value = add(a, b if b == 2 else c, d)

*don't declare sum as variable it is an an inbuilt function of python *

Related