0
d = 666
def default_due(a, b=d):
 print('a =', a, 'b =', b)
d = 0
default_due(11)
default_due(22,33)

I don't understand why this prints

a = 11 b = 666
a = 22 b = 33

And not

a = 11 b = 0
a = 22 b = 33
  • 1
    See also https://stackoverflow.com/questions/1651154/why-are-default-arguments-evaluated-at-definition-time-in-python – Karl Knechtel Feb 28 '20 at 11:58
  • 1
    Does this answer your question? [Why are default arguments evaluated at definition time in Python?](https://stackoverflow.com/questions/1651154/why-are-default-arguments-evaluated-at-definition-time-in-python) – tomgalpin Feb 28 '20 at 11:59
  • Because you're not modifying the value of d inside that default_due function. so that d will remain 666 and will not change to 0 if you only prints(d) then it will be 6 – Juhil Somaiya Feb 28 '20 at 12:03

2 Answers2

2

This happens because the default arguments b=d is evaluated only once when the function is defined. After that, the value of d inside the function does not change.

Read more here

ybl
  • 1,510
  • 10
  • 16
0

As you are not passing the value for the second parameter, the default value is used. But, in the second case, when the value for second parameter is also passed, then the default value is overridden with the new value. Hence, this results in the output you've observed. You can even verify the results.

For more detailed explaination, see this:

GeeksForGeeks

taurus05
  • 2,491
  • 15
  • 28