1

Let's say I have 3 variables & a function func:

a=1;b=1;c=1
def func(a=a,b=b,c=b/a):
    print(a,b,c)

To my surprise, func(b=2) produces an output:

1 2 1.0

Why is c not b/a, ie not 2/1=2?

How can I make the function recalculate the c when called, if either non-default a or b (ie either of them doesn't equal 1) is passed?

zabop
  • 6,750
  • 3
  • 39
  • 84

1 Answers1

2

if you want to c have a default value when nothing is passed, make c=None in functional argument and set default value inside function when no value of c is passed

a=1;b=1;c=1
def func(a=a,b=b,c=None):
    c = c if c is not None else b/a
    print(a,b,c)

Note: earlier solution fail when c=0 so updated as suggested by @MisterMiyagi
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
  • Thank you. Can confirm that this does indeed work if `c` is a number initially (tried with 0 and 1). Could you elaborate on how the `if c` bit works? I notice that this method fails if `c` is initially set to the value `False`, but this is quite a special case. – zabop Mar 02 '21 at 18:12
  • 1
    this answer is based on if c is of type int. [how `if c` work](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) , this only fails when you set c to True not False as then it provide output True for c. Note answer based on all argument is of type int – sahasrara62 Mar 02 '21 at 18:18
  • 1
    This will fail when passing in ``c=0``, e.g. ``func(1, 2, 0)``. The check should explicitly test ``... if c is not None else ...`` – MisterMiyagi Mar 02 '21 at 18:38
  • @MisterMiyagi updaed solution – sahasrara62 Mar 02 '21 at 18:59