0

This is been killing me. When using the following code to print the Fib number, it gives the right output:

a = 0
n = 1
while n < 55:
    print(n)
    a,n = n,a+n

but when I change to this:

a = 0
n = 1
while n < 55:
    print(n)
    a = n
    n = a+n

The output is totally different. I've even run it thru pythontutor.com to watch stepping.

What are I missing.

3 Answers 3

1

There is a difference in the way variable values are interpreted and assigned between the two code snippets.

In case of the first snippet, while assigning the value to "n", the new value of a is not used, rather the value of a from the previous iteration is used.

But, in case of the second snippet, the value of "a" is first updated and then used for the second statement.

Let's take an example:

For the first iteration where n is 1,

First Code Snippet: At the end of the iteration, the value of a will be 1 and value of n also will be 1. (For n = a+n, value of a is considered 0)

Second Code Snippet: At the end of the iteration, the value of a will be 1 and value of n will be 2. (For n = a+n, value of a is considered 1)

The key point to be noted about the Python Comma Operator is that, all the expressions to the right of the assignment operator are evaluated first before the assignments are actually made and this causes the difference in output between the two.

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

Comments

0

Well, the initial assignment

 a,n = n,a+n

means

 old_a = a
 a = n
 n = old_a + n # saved a value (old_a) used 

Please, notice that n = old_a + n, not a + n == 2 * n

Comments

0

Let's call a_i and n_i the values of a and n at the i-th iteration. In the first code you are assigning to n_i+1 the value a_i + n_i, instead in the second code you are assignign to n_i+1 the value a_i+n_i+n_i. This happen because you are assigning a before n in the second code, while this happen simultaneously in the first one. To solve this issue save in a temporary variable the old value of n or a.

Alternatively, with just a bit of math, you can do the following without saving any temporary variable:

a = 0
n = 1
while n < 55:
    print(n)
    n = a+n
    a = n-a

which is equivalent to: a_i+1 = n_i+1 - a_i = a_i + n_i - a_i = n_i.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.