0

Python iteration? Why code1 != code2

#code 1 x=2 x,x=x+3, x+4 print(x) #code 2 x=2 x=x+3 x=x+4 print(x)

26th Nov 2019, 9:16 PM
Storm Yule
Storm Yule - avatar
4 ответов
+ 3
In code1 x+3 doesn't apply until after x+4. so we'll have x=x+4=> x=6. This is a rule in such situations. For example: x, y = y, x In the above if x=y be applied first then no swap will be taken effect and both variables will be equal to primary value of y.
26th Nov 2019, 9:44 PM
Qasem
+ 1
Thanks for your answer, Qasem!
26th Nov 2019, 9:47 PM
Storm Yule
Storm Yule - avatar
+ 1
HI there Storm, #code 1 = 6 #code 2 = 9 Working out the result of #code 2 manually was no problem. How exactly line 3 of #code 1 is calculated I'm not sure. I use a tool on Python Tutor frequently to visualise how code works. You may find it useful in the future: Try plugin your code into this tool: http://pythontutor.com/visualize.html#mode=edit and let me know how you get on
26th Nov 2019, 9:59 PM
Stuart Peel
+ 1
Thank you Stuart, very useful tool.
26th Nov 2019, 10:29 PM
Storm Yule
Storm Yule - avatar