Reputation: 53
I am relatively new to Python, so pardon my ignorance.
These two implementation of while loop for generating a Fib series is resulting in very different outputs.
The first one is returning the power series of 2, though I feel it is should be doing exactly what the latter is; which is returning the expected series.
The second while loop is obviously doing something right. I am guessing it has to do with the way the variables as being assigned while swapping values.
What is driving this difference?
Appreciate your inputs and help,
First while loop:
def fib(n):
x=0
y=1
while y < n:
print(y)
x = y
y = x + y
The second while loop:
x,y=0,1
while y < 100:
print(y)
x,y = y,x+y
Upvotes: 1
Views: 7959
Reputation: 22
Edited Answer:
No prob. Following the sequence of your first loop, so x=0, y=1
. The first line in your loop makes x = y = 1
.
So now y=1
.
Then, your next line creates y=x+y
.
Which means y=1+1=2
. Now x=1
and y=2
.
For the next iteration:
x = y = 2
so x = 2
then:
y= 2 + 2 = 4
As was explained, your second loop is a parallel assignment. So following the logic starting with x=0
and y=1
:
x,y=y,x+y
causes:
x=1 and y= 0+1 = 1 simultaneously
So now x=1
and y=1
. Then for the next iteration:
x=1 and y= 1+1=2 simultaneously
So now x=1
and y=2
. My professor for my computer science class taught me that following code line by line on paper helps understand the process the computer follows. I also found it was good to help build an ability to read code. Hope this helped.
Upvotes: 0
Reputation: 54223
x,y = y,x+y
This is a parallel assignment. The x
on the right side is still the old x
, it hasn't been set to y
yet. This is the desired behaviour, for example in order to swap two variables without needing a 3rd one:
>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
2
>>> b
1
As explained by @Alfe, x, y = y, x + y
is actually one single tuple assignment:
(x, y) = (y, x + y)
The tuple on the right is completely defined before the assignment happens.
x = y
y = x + y
The x
on the right side of the second line has been set to y
on the previous line, so the second line is actually y = y + y
.
If you try to swap two variables this way you'll get the same value twice:
>>> a = 1
>>> b = 2
>>> a = b
>>> b = a
>>> a
2
>>> b
2
You need a third variable:
>>> a = 1
>>> b = 2
>>> temp = b
>>> b = a
>>> a = temp
>>> a
2
>>> b
1
Upvotes: 3