Which of the following expressions is equivalent to the expression in the function?

You develop a Python application for your company.

You have the following code.

def main(a, b, c, d):

value = a + b * c – d

return value

Which of the following expressions is equivalent to the expression in the function?
A . (a + b) * (c – d)
B. a + ((b * c) – d)
C. None of the above.
D. (a + (b * c)) – d

Answer: D

Explanation:

Topics: addition operator multiplication operator

subtraction operator operator precedence

Try it yourself:

def main(a, b, c, d):

value = a + b * c – d # 3

# value = (a + (b * c)) – d # 3

# value = (a + b) * (c – d) # -3

# value = a + ((b * c) – d) # 3

return value

print(main(1, 2, 3, 4)) # 3

This question is about operator precedence

The multiplication operator has the highest precedence and is therefore executed first.

That leaves the addition operator and the subtraction operator

They both are from the same group and therefore have the same precedence.

That group has a left-to-right associativity.

The addition operator is on the left and is therefore executed next.

And the last one to be executed is the subtraction operator

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments