Tuesday, 15 March 2011

python - Why does this code only work when i use 'x,y = y,x + y format instead of 'x = y; y = x + y'? -



python - Why does this code only work when i use 'x,y = y,x + y format instead of 'x = y; y = x + y'? -

i working on project euler, that's beside point though. writing quick code print out fibonacci sequence. have different code project eueler equation, algorithm using:

x = 1 y = 0 while x < 4000000: print x x = y y = x + y

this erking me awhile, should have worked. researched bit , found virtually same code in tad bit different of format. , worked! difference set x , y assignments single line, separated comma. tried it:

x , y = 1 , 0 while x < 4000000: print x x,y = y, x + y

obviously, said, worked. bothering me can't figure out difference between 2 other beingness clever , using less lines in sec one. cant understand why output different. why output different?

in first code:

x = y y = x + y

you assigning y + y y. since value of x overwritten. , not wanted right?

and in 2nd code:

x, y = y, x + y

first y , x + y on rhs evaluated, , evaluated value assigned x, y on lhs. so, x + y not have side-effect of newly assigned value x, happening in first case. so, y have x + y.

so, it's case of evaluation of both look on rhs, before actual assignment done.

and yes, assignments outside while loop, not create difference. 2nd way looks more appealing.

python variables

No comments:

Post a Comment