nerdexam
Python_Institute

PCEP-30-02 · Question #110

What is the expected output of the following code? `` 1 x = 0 2 y = 1 3 x = x ^ y 4 y = x ^ y 5 y = x ^ y 6 print(x, y) ``

The correct answer is E. 1 1. Option E is correct because this code looks like the classic XOR swap algorithm but has a subtle bug on line 5: it reassigns y a second time instead of assigning x. Tracing through: x = 0^1 = 1, then y = 1^1 = 0, then y = 1^0 = 1 - so both end up as 1. Why the distractors fail…

Question

What is the expected output of the following code?
1 x = 0
2 y = 1
3 x = x ^ y
4 y = x ^ y
5 y = x ^ y
6 print(x, y)

Options

  • A0 1
  • B1 0
  • CThe code is erroneous.
  • D0 0
  • E1 1

How the community answered

(39 responses)
  • A
    3% (1)
  • B
    3% (1)
  • C
    5% (2)
  • D
    13% (5)
  • E
    77% (30)

Explanation

Option E is correct because this code looks like the classic XOR swap algorithm but has a subtle bug on line 5: it reassigns y a second time instead of assigning x. Tracing through: x = 0^1 = 1, then y = 1^1 = 0, then y = 1^0 = 1 - so both end up as 1.

Why the distractors fail:

  • A (0 1) - the original values, as if no XOR operations ran at all
  • B (1 0) - what a correct XOR swap would produce (line 5 would need to be x = x ^ y)
  • C (erroneous) - XOR (^) is valid Python syntax for integers; the code runs fine
  • D (0 0) - no XOR combination of these values produces two zeros here

Memory tip: The XOR swap pattern is x=x^y, y=x^y, x=x^y - notice the last line must reassign x, not y. When you see the pattern broken (two y= assignments in a row), the swap is incomplete and y "bounces back" to its original value.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice