Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Trouble Understanding Why This Code Works
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)

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,
Yoriz wrote Apr-05-2019, 03:24 PM:
Great first post, i had to fix the python tags / was missing but you tried and all the info is there. well done
Yoriz likes this post
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!

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  importing datetime trouble Dixon 4 979 1 hour ago
Last Post: satishm
  understanding output of bytes/raw data rootVIII 3 200 Aug-01-2019, 01:00 PM
Last Post: rootVIII
  Trouble processing file villumanati 1 75 Jul-30-2019, 04:17 AM
Last Post: Larz60+
  Coding understanding help srikanth 1 89 Jul-19-2019, 09:12 AM
Last Post: Larz60+
  The following script works but I need to take it one step further to milliseconds. yeto 1 160 Jul-19-2019, 04:15 AM
Last Post: micseydel
  Trouble importing modules on a new python version snackman_barry 2 148 Jul-12-2019, 11:15 AM
Last Post: snackman_barry
  More Python Embedding Trouble jibarra 3 179 Jul-11-2019, 09:25 PM
Last Post: Gribouillis
  Raspberry - Python 3.7 - Installation trouble madjo1983 2 192 Jul-07-2019, 02:06 AM
Last Post: DeaD_EyE
  Simple while loop only works on first attempt jsb83 2 173 Jun-20-2019, 08:57 PM
Last Post: jsb83
  understanding exponential and bitwise operators srm 1 162 Jun-15-2019, 11:14 AM
Last Post: ThomasL

Forum Jump:

Users browsing this thread: 1 Guest(s)