PCEP-30-02 · Question #216
``python def test(x=1, y=2): x = x + y y += 1 print(x, y) test() `` What is the expected output of the following code?
The correct answer is B. 33. Option B (3 3) is correct because when test() is called with no arguments, the defaults x=1 and y=2 are used. The first line inside the function sets x = 1 + 2 = 3, then y += 1 increments y from 2 to 3, so print(x, y) outputs 3 3. Why the distractors are wrong: A (1 3)…
Question
def test(x=1, y=2):
x = x + y
y += 1
print(x, y)
test()
What is the expected output of the following code?Options
- A13
- B33
- CThe code is erroneous.
- D11
- E31
How the community answered
(23 responses)- B78% (18)
- C4% (1)
- D13% (3)
- E4% (1)
Explanation
Option B (3 3) is correct because when test() is called with no arguments, the defaults x=1 and y=2 are used. The first line inside the function sets x = 1 + 2 = 3, then y += 1 increments y from 2 to 3, so print(x, y) outputs 3 3.
Why the distractors are wrong:
- A (1 3) - Assumes
xwas never updated, butx = x + yreassigns it to3, not leaving it as1. - C (erroneous) - The code is perfectly valid Python; default parameters and in-place arithmetic are both legal.
- D (1 1) - Misreads both operations entirely; neither value stays at
1after execution. - E (3 1) - Gets
xright but confusesy += 1as subtracting or resetting;ygoes from2to3, not down to1.
Memory tip: Trace assignments top-to-bottom and remember that default parameters are only the starting values - any reassignment inside the function immediately replaces them. Write out each variable's value after every line to avoid mix-ups.
Community Discussion
No community discussion yet for this question.