Trouble Understanding Why This Code Works - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Trouble Understanding Why This Code Works (/thread-17299.html) |
Trouble Understanding Why This Code Works - crocolicious - Apr-05-2019 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 erroneousThanks again to the Community, crocolicious RE: Trouble Understanding Why This Code Works - Yoriz - Apr-05-2019 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, 2with 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, 0then the print is in the order of x, y, z print(x, y, z) RE: Trouble Understanding Why This Code Works - crocolicious - Apr-09-2019 Thank you Yoriz for your help! |