ThisisFish
ThisisFish

Reputation: 456

is there any different behaviour between single var assignment and multiple var assignment in python?

i have a function which will print Fibonacci series

def fib(n):
    """ print the fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
      print(a)
      a, b = b, a + b

which works just fine. but when i change some coding style it does not work as i intended. so what is happening here ?

def fib(n):
    """ print the fibonacci series up to n."""
    a = 0
    b = 1
    while a < n:
       print(a)
       a = b
       b = a + b

above code does not print same result as first code but i can see same code in both function. i m beginner in python.

Upvotes: 1

Views: 74

Answers (2)

Santosh Karki
Santosh Karki

Reputation: 97

Well, you have not correctly swap the values in the second method

Straight forward solution is:

def fib(n):
    a = 0
    b = 1
    while a < n:
        print(a)
        c = a + b   # c is the temporary variable
        a = b
        b = c

In first method, addition gets evaluated first then a becomes b and b becomes the added value. Whereas in the second method you store added value in some other variable then you do swap the value as shown above code.

Upvotes: 0

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

Yes, there is different behavior. Everything on the right side of the = gets evaluated before any of it gets assigned to the left side of the =. Multiple assignment just means that you compute a tuple on the right side, and assign it to a tuple on the left side.

a, b = b, a+b
# computes (b, a+b)
# matches with (a, b)
# assigns the computed values to a and b respectively

versus

a = b
# assigns the value of b to a
b = a + b
# computes a + b (since a was just set equal to b, this is the same as b + b)
# assigns that computed value to b

If you need to have all your assignments on separate lines, then you'll either need a temporary holding variable for swapping a and b:

temp = a
a = b
b = b + temp

or do something fancy to preserve the difference between b and a:

b = b + a
a = b - a

Multiple assignment is the "most correct" solution to the problem, mainly because it's the most concise.

Upvotes: 3

Related Questions