-1

I have a question on how "," versus what would be \n In python 3.+

#There is technically a "\n" in between this two values (BA & BB)
BA=6 
BB=90

But shouldn't it be interpreted the same was as this?

BA,BB = 6,90

Correct? The reason I'm asking this is because of how this while loop is interpreting it.

a ,b = 0,1
while b <100:
    print(b)
    a,b = b, a+b

Is not the same as:

a=0
b=1    
while b <10:
    print(b)
    a=b
    b = a+b

The first while loop gives me a Fibonacci output but the second while loop gives me a duplication. Output of second while loop:

1 
2 
4 
8 
4 

Could some one explain?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Droid
  • 17
  • 4
  • I point you at [`dis`](https://docs.python.org/2/library/dis.html) if you want to know specifics, but, no, they are not the same. the first variant is equivalent to `(a,b) = (b, a+b)`. The second , well, sets `a` to `b`, and then tries to add `a` (which is now `b`) to `b` – NightShadeQueen Jul 19 '15 at 04:11

1 Answers1

0

This is because the values of a and b are updated at the end of the statement, which means that you can pass the value of b to a before it becomes a+b.

In the first loop, here is what happens:

1    a becomes b=1 & b becomes a+b=0+1=1
2    a becomes b=1 & b becomes a+b=1+1=2
3    a becomes b=2 & b becomes a+b=1+2=3
4    a becomes b=3 & b becomes a+b=2+3=5

However, in the second loop, these events are separated, so:

1    a becomes b=1
     b becomes a+b=1+1=2
2    a becomes b=2
     b becomes a+b=2+2=4
3    a becomes b=4
     b becomes a+b=4+4=8

As you can see, in each iteration of the second loop, you are effectively just doubling the value of b. If you wanted to avoid setting both variables on the same line, you would need to define a 3rd variable, which was equal to the old value of a:

a=0
b=1    
while b <100:
    print(b)
    old_a = a;
    a=b
    b = old_a+b

This loop will work as you expect.

GJStein
  • 648
  • 5
  • 13