1

I am new to both programming (both in general and in Python) and to this community.

Following are two versions of the Fibonacci code, one attempted by me on my own, and the other from the Python documentation. The latter works but mine does not, and the only difference I can see between the two codes is that I have reassigned "a" and "b" on different lines in the while loop, whereas the one from Python doc. has assigned them on the same line.

In fact, when I reassign new values for a and b in my code on the same line, I get the correct output - but I dont know why? Why does it matter in this case on which line the values are reassigned?

#My own version of the fibonacci code. o/p as 1 2 4 8
a, b=0,1
while b<10:
    print(b, end=" ")
    a=b
    b=a+b

#Python's doc version which works
a, b = 0, 1
while b < 10:
    print(b, end=" ")
    a, b = b, a+b
Neild
  • 11
  • 1
  • 2
    In your version, `a` has changed by the time it gets to the assignment to `b`. In the doc version the original `a` is used for the assignment (the right-side is interpreted before the assignment) – cdarke Apr 27 '18 at 07:07
  • `a, b = b, a+b` performs the assignments in parallel. Your version changes `a` then uses it to calculate `b`. – PM 2Ring Apr 27 '18 at 07:07
  • The reason for that is because `while` loop checks the correctness of its condition one operation at a time and when you reassign those variables at one line since the value of `b` is related to those operations it performs differently in each code. In more details when you do: a=b b=a+b `a` gets update by the value of `b` and in next line `b` is actually `2b`. But when you do: a, b = b, a+b `a` gets update but since `b = a+b` is performed at the same like `a` has it's previous value not the current `b`. – Mazdak Apr 27 '18 at 07:11
  • 2
    I would also suggest in such cases that you use print so you can see a step by step execution. In each loop you can see what value is assigned to the variable you are interested in. If you use print you can see from the first loop execution there is a difference and then you can further analyse the behavior of your program and the behavior that you want to achieve – Gerasimos Ragavanis Apr 27 '18 at 07:11

2 Answers2

1

In your code a gets the value of b before the summation

a = b <---- a gets updated
b = a+b <--- summation

In the doc version, a never gets an updated value before the summation as its done on the same line. Values of a and b are updated after this line.

a,b = b, a+b
svenovic
  • 31
  • 1
0

Because in your version, when you are writting b=a+b, you just write before a=b so the line is b=a+a.

In the other version, there is a, b = b, a+b But in this one, b is changing at the same time than a.

(if you want, you could say

a1, b1 = b0, a0+b0

and you line would be :

a1=b0
b1 = a1 + b0

)

LudwigVonKoopa
  • 208
  • 4
  • 13