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
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)- A3% (1)
- B17% (5)
- C7% (2)
- D73% (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 assumesyretains its value after the swap, ignoring thaty = zreassigns it to1. - C (
1 1) is wrong because it assumesxnever changes, ignoring thex = yassignment.
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.