Search code examples
pythonfor-loopwhile-loopvariable-assignmentfibonacci

Variable assignment difference


I'm currently on an exercise to produce the position of a given Fibonacci number.

My initial code was :

n = int(input())
a = 0
b = 1
new_list = []

for i in range(n+1):
    new_list.append(a)
    a = b 
    b = a + b 

print(new_list)

However, The right way to execute the code is :

n = int(input())
a = 0
b = 1
new_list = []

for i in range(n+1):
    new_list.append(a)
    a, b = b, a + b

print(max(new_list))

What's the difference between a,b = b, a + b and a = b, b += a written in separate lines?

I asked for help from ChatGPT, but I don't quite understand the difference between my code and the corrected code, given that my code returns the wrong answer and ChatGPT is correct.


Solution

  • The right-hand side is fully evaluated before performing the assignment. In the second second snippet, you'd first add a+b, and then assign a=b and b=a+b, where the value of a is taken before it's overridden with b.

    In the first snippet, a is overriden with b, and then b is assigned a+b, which just doubles its value.

    If you wanted to separate the assignments for better readability, you could use a temporary variable:

    tmp = a + b
    a = b
    b = tmp