Python Forum
Two same codes, different result. Please help to understand.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Two same codes, different result. Please help to understand.
#1
why there is two different output for similar codes.
This below code gives proper Fibonacci
def fib(n) :
    a,b= 0,1
    for x in range(n):
            print(a)
            a,b=b,a+b
Output: 0,1,1,2,3,5,8


While this code does not give proper Fibonacci series
def fib(n) :
    a,b= 0,1
    for x in range(n):
            print(a)
            a=b
            b=a+b
Output: 0,1,2,4,8

Please help me understand the execution process in python.
Reply
#2
well on line 5 a takes the value of b, so line 6 is the same as b = b + b
You can use debugger or print value of a after line 5 to see what happens

def fib(n) :
    a,b= 0,1
    for x in range(n):
        print(a)
        c=b
        b=a+b
        a=c
            
fib(7)
Output:
0 1 1 2 3 5 8
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
@buran,

Then how does the interpreter read
 a,b=b,a+b
how would you write this in two row. ?
Reply
#4
The main thing here, is that a, b = b, a+b is NOT the same as a = b; b = a+b.

The first one creates a temporary tuple with the original values of both a and b, before either is bound to a new value. While in the second, a is given a new value, and then that new value is used to compute a new value for b.

As was pointed out by buran, the way to do it without tuple unpacking would be to create a temporary variable to hold the original value of either a or b. So either:
temp = a
a = b
b = temp + b
...or...
temp = b
b = a + b
a = temp
Reply
#5
the right hand side is evaluated fully before the assignment
so first b, a+b is evaluated and you get a 2-element tuple
then it is unpacked in a,b, i.e. 0-index element is assigned to a and 1-index element is assigned to b

I gave you example, you need third variable (the intermediate variable - in my example c) to temporary hold the old value of b
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
Thanks a lot guys.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I don't understand this result Ponomarenko Pavlo 5 3,821 Mar-27-2017, 02:04 PM
Last Post: buran
  I don't understand this result Ponomarenko Pavlo 3 3,763 Jan-15-2017, 04:40 PM
Last Post: Kebap

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020