Python Forum

Full Version: Trouble Understanding Why This Code Works
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Community,
I'm studying a practice exam and the following question does not make sense to me. The answers have been provided but I'm still unsure how this answer was arrived at.

Which line can be used instead of the comment to cause the snippet below to produce the following expected output? (Select all that apply)

Code:
z, y, x = 2, 1, 0 
x, z = z, y
y = y - z 

# put line here 

print(x, y, z)
Expected output: 0, 1, 2

The available choices are below. The answer key says that both A and B answers are correct but I don't understand the logic in how they're both right. I tested both of them in a real environment (Python 3.7 using Spyder IDE) and they do work to produce the expected output. Can someone please help me understand WHY they both work? Many thanks in advance for your help. It is greatly appreciated!
A. x, y, z = y, z, x
B. z, y, x = x, z, y
C. y, z, x = x, y, z
D. The code is erroneous
Thanks again to the Community,
crocolicious
After running
z, y, x = 2, 1, 0 
x, z = z, y
y = y - z 

print(x, y, z)
you can realise that x = 2, y = 0 & z = 1

with the variables that are being assigned to in the same order as the final print, the variables on the right are arranged to give correct order
x, y, z = y, z, x # same as x, y, z = 0, 1, 2
with with the variables that are being assigned to in the reverse order of the final print, the variables on the right are also arrange to give the reverse order.
z, y, x = x, z, y # same as z, y, x = 2, 1, 0
then the print is in the order of x, y, z
print(x, y, z)
Thank you Yoriz for your help!