Reputation: 99
Say I want to build a function that either adds two numbers a
and b
, or subtracts them and adds a third number c
and subtracts the fourth number d
. I intend to specify which of the two operations is to be performed by an argument sum
; if this is True
, the first operation is performed, if False
, then the second operations is performed. I would write this as:
def f(a, b, c, d, sum=True):
if sum: return a+b
else: return a-b+c-d
For example, f(1,2,3,4)
returns 3
, while f(1,2,3,4,sum=False)
returns -2
, as expected. Clearly, though, c
and d
only need to be defined when sum=False
. How do I do this? I've tried setting c
and d
as *args, but I keep getting errors of the type "unsupported operand" or "positional argument follows keyword argument".
Upvotes: 1
Views: 156
Reputation: 42592
Others have given the way you can do it, but at a more fundamental level I'd ask why this is even the same method? Seems to me you have two different methods here, f_sum and f (or whatever), one takes two parameters and the other 4.
Or if it's a more complex operation and c and d are just additional parameters / attributes, you could default them to whatever the null value is e.g. for addition just default them to 0:
def f(a, b, c=0, d=0)
a+b-0+0
won't do anything so if these parameters are not provided the result will be identical to a+b without even needing a conditional or magical flag.
sorry missed that the second case was a -
b and misread it as a +
Upvotes: 3
Reputation: 797
The answer to your question is:
def f(a, b, c=None, d=None, sum=True):
if sum: return a + b
else: return a - b + c - d
However, you could further simplify it to this:
def f(a, b, c=0, d=0):
return a - b + c - d
As the values of c and d depend on whether sum
is true or false.
Upvotes: 1
Reputation: 130
This solves your problem:
def f(a, b, c=0, d=0, sum=True):
if sum: return a+b
else: return a-b+c-d
Upvotes: 1
Reputation: 7529
Use a default value of None
for c and d:
def f(a, b, c=None, d=None, sum=True):
if sum:
return a+b
else:
return a-b+c-d
This also allows you to add error-checking logic to your function - check whether c and d are present when sum is False:
def f(a, b, c=None, d=None, sum=True):
if sum:
return a+b
else:
if None in (c, d):
raise TypeError('f requires c and d args with parameter sum=False')
return a-b+c-d
Upvotes: 3