0

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))
3
  • 5
    Hint: What if neither of the if conditions is true? What will be returned? And why do you make it all the more confusing by swapping the meaning of x and y when setting the local variables with the same name? Commented Jun 15, 2022 at 14:55
  • this is actually from a python course that i am taking.. Commented Jun 15, 2022 at 14:59
  • And the course is not explaining what it is supposed to explain? Commented Jun 15, 2022 at 15:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! You have explained it better than the lecturer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.