Search code examples
pythonfunctiondefault

Dafault value of function


For the program below:

x=12
def f1(a,b=x):
    print(a,b)
x=15
f1(4)

Why the output is 4 12 but not 4 15? The function will not take the most updated value of x right before it is being called? But will only take the value right before it is being defined?


Solution

  • The value of b is set when the function is defined. If you'd like for it to be set when the function is called, you'll have to do it yourself in the function with something like:

    def f1(a, b = None):
        if b is None:
            b = x
        print(a, b)