Can anyone help me understand why is the output of the following code snippet = None?
def func(x, y):
"""This is a function"""
if x%3 == 0:
return x
elif x%3 == 1:
return y
x = 1
y = 2
print(func(y=x, x=y))
Debugging -- stepping through the code and inspecting variables -- should make it all clear:
Just before the function is executed, the global variables x and y have already received their values:
x: 1
y: 2
Then the arguments are passed to the function. In this case they are passed by specifying their corresponding parameter names -- using key = value syntax: With y=x the parameter y (a local variable in the function's context) gets the value of the global variable x. And with x=y the parameter x gets the value of the global variable y. The order in which these arguments were passed is irrelevant, because they were passed as keyword arguments, not as positional arguments.
When execution enters the function body, we have two local variables x and y and we can see they have these values:
Globals Locals
x: 1 x: 2
y: 2 y: 1
The global variables are not accessible in this function, since they are shadowed by the local variables with the same names (but different values!)
The first if condition is false, because 2%3 is 2, not 0. The second if condition is also false as this expression is not 1 either. And so no return statement gets executed. Instead the function exits with the default return value, which is None, which is also the printed value.
ifconditions is true? What will be returned? And why do you make it all the more confusing by swapping the meaning ofxandywhen setting the local variables with the same name?