nerdexam
Python_Institute

PCEP-30-02 · Question #119

What will be the output of the following code snippet? ``python x = 1 y = 2 z = x x = y y = z print(x, y) ``

The correct answer is D. 2 1. Option D (2 1) is correct because the code performs a classic variable swap using a temporary variable: z captures the original value of x (which is 1), then x is overwritten with y's value (2), and finally y is restored to the original x via z (1), yielding x=2, y=1. A (1 2)…

Question

What will be the output of the following code snippet?
x = 1
y = 2
z = x
x = y
y = z
print(x, y)

Options

  • A1 2
  • B2 2
  • C1 1
  • D2 1

How the community answered

(30 responses)
  • A
    3% (1)
  • B
    17% (5)
  • C
    7% (2)
  • D
    73% (22)

Explanation

Option D (2 1) is correct because the code performs a classic variable swap using a temporary variable: z captures the original value of x (which is 1), then x is overwritten with y's value (2), and finally y is restored to the original x via z (1), yielding x=2, y=1.

  • A (1 2) is wrong because it reflects the original values - as if no swapping occurred at all.
  • B (2 2) is wrong because it assumes y retains its value after the swap, ignoring that y = z reassigns it to 1.
  • C (1 1) is wrong because it assumes x never changes, ignoring the x = y assignment.

Memory tip: Trace variable swaps step-by-step in a table - write out each variable's value after every line. The temporary variable (z) is the key: it's a "snapshot" of x before it gets overwritten, allowing the swap to complete without data loss.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice