Hoffman - 4 months ago 22

Python Question

I'm new to python so I want to ask you a question..

Previously while I was writing a fibonacci function I tryed to replace

`a, b = b, a+b`

with

`a = b`

b = a + b

Believing that it was the same thing but I noted that the output is different (and wrong)

Shouldn't these two codes do the same thing?

Here it is the full code:

`#!/usr/bin/env python`

# -*- coding: utf-8 -*-

def main(args):

fibonacci(1000)

return 0

def fibonacci(n):

a, b = 0, 1

while b < n:

print b,

a, b = b, a+b # if I comment this and decomment the two line below it shows me a different output

# a = b

# b = a + b

if __name__ == '__main__':

import sys

sys.exit(main(sys.argv))

Answer

when you do:

```
a, b = b, a+b
```

`a`

will hold the previous value of b and `b`

will hold `a+b`

based on previous value.

But when you do:

```
a = b
b = a + b
```

Value of `a`

is updated to `b`

during `a=b`

and hence `a+b`

will have different result as `a`

is now updated.

For example, see simple code to swap two values. It is possible because of the on the fly change in values:

```
>>> a , b = 5, 10
>>> a, b = b, a
>>> a, b
(10, 5)
```