How multiple operator works

0 Are Riff · August 18, 2015
I got this from the documentation. the Fibonacci series:
1  def fib(n):
2      a, b = 0, 1
3      while a < n:
4           print(a, end=' ')
5           # a, b = b, a+b # This is the original line
6           a = b                # Tried replacing with these lines
7           b = a+b            # This too
8      print()
9  fib(100)

My question is, why it produces wrong result (with line 6 and 7)
How (a,b = b, a+b )  is different from (a=b and b=a+b) ???

Post a Reply

Replies

Oldest  Newest  Rating
0 Otto Von Chesterfield · August 19, 2015
First, make sure to cover your code with the code tag.
#It looks something like this.

It makes the code much easier to read. The code button is the piece of paper with the <> to the left of the dialogue box.


Next.

By defining a to be b before you say b = a+b, by algebra, you're saying that b = b+b, or b = 2*b.

Why a, b = b, a+b works is that a in b = a+b does not change - it's still a.

It sounds confusing, but in summary, by doing both operations at the same time, each computation works as if none of the equations happened yet.
0 Are Riff · August 19, 2015
It is taken from the python documentation.
The to working code is

a, b = b, a+b

So, I thought that is more difficult to read. So, I tried to break the lines into two:

a = b
b = a + b

logically (for me) it is the same. So I comment out the original code to test the new one. But it gave different result, means that I was wrong. But why?
0 Otto Von Chesterfield · August 20, 2015
a, b = b, a+b happens at the same time. In order to do the same thing, you have to do:

c = a #Store the 'a' variable in c...
a = b #Because 'a' is changed here.
b = c + b # Add the previous value of a to itself


In this line of code:
a, b = b, a+b

A hasn't changed yet when also calculating b.


Also, use the code block. It's for the better.
  • 1

Python

107,031 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator