What is the output of the following snippet?

What is the output of the following snippet?

def fun(x, y, z):

return x + 2 * y + 3 * z

print(fun(0, z=1, y=3))
A . the snippet is erroneous
B. 9
C. 0
D. 3

Answer: B

Explanation:

Topics: positional parameter keyword parameter operator precedence

Try it yourself:

def fun(x, y, z):

return x + 2 * y + 3 * z

print(fun(0, z=1, y=3)) # 9

print(0 + 2 * 3 + 3 * 1) # 9

print(0 + (2 * 3) + (3 * 1)) # 9

print(0 + 6 + (3 * 1)) # 9

print(0 + 6 + 3) # 9

print(6 + 3) # 9

print(9) # 9

The function here works fine.

The keyword arguments do not have to be in the correct order among themselves as long as they are all listed after all positional arguments.

And because multiplication precedes addition 9 gets returned and printed.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments