0

I am learning python and I have some question:

What is the difference between

a,b = 0,1
for x in range(100):
    print(a)
    a=b
    b=a+b

and

a,b = 0,1
for x in range(100):
    print(a)
    a,b = b, a+b

First one gives bad result, but why?

4
  • This is good to go through with pen and paper. Write down the values of the variables, then update them step by step. Commented Jan 23, 2017 at 12:05
  • In the first example you assign a new value to A before assigning a value to B. In the second case you do it simultaneously. Commented Jan 23, 2017 at 12:05
  • Because a has changed and thus a + b will be different. Assignment calculates the results of the right hand side before applying the results to the left. Commented Jan 23, 2017 at 12:05
  • stackoverflow.com/a/8725769/5033247 Commented Jan 23, 2017 at 12:07

1 Answer 1

1

Because you first set a = b, your new b will have the value of twice the old b. You overwrite a to early. A correct implementation should use a temporary variable t:

a,b = 0,1
for x in range(100):
print(a)
    t=a
    a=b
    b=t+b

This is basically what you do by using sequence assignment.

In your original code you have:

a,b = 0,1
for x in range(100):
    print(a)
    a=b # a now is the old b
    b=a+b # b is now twice the old a so b'=2*b instead of b'=a+b

So this would result in jumping by multiplying with two each time (after first loading in 1 into a the first step).


An equivalent problem is the swap of variables. If you want a to take the value of b and vice versa, you cannot write:

#wrong swap
a = b
b = a

Because you lose the value of a after the first assignment. You can use a temporary t:

t = a
a = b
b = t

or use sequence assignment in Python:

a,b = b,a

where a tuple t = (b,a) is first created, and then assigned to a,b.

Sign up to request clarification or add additional context in comments.

8 Comments

You on Windows or Linux?
@MYGz: Linux of course, why?
Why do you write <code><pre> There is a chrome extension called text area formatter, You can select the code part and indent it with tab.
@MYGz: well usually it is as fast as writing code itself (the formatting part) when using an advantage kinesis :) Every swap between keyboard and mouse is a waste of time.
Are you telling me select code and press a tab can sometimes be slower for you than writing <pre><code></code></pre>. I can never reach those typing speeds :D
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.