Last answered:

09 Aug 2022

Posted on:

25 Oct 2021

2

Wrong code for Fibonacci Bumbers, why?

Hi! For question 7, the last line of code is:

a, b = b, a+b.

I assume this is the same as writing 2 lines of code:

a = b
b = a+b

But I get another result, not the Fibonacci numbers, why?

4 answers ( 0 marked as helpful)
Instructor
Posted on:

26 Oct 2021

0

Hey Juan,

Thank you for the good question!

As it turns out, the line of code

a, b = b, a+b

is not equivalent to

a = b
b = a+b

Let us take a = 0 and b = 1. Performing the first line of code above would be equivalent to

a, b = 1, 0+1

Note how we are using the old values of a and b.
Now, if we again take a = 0 and b = 1 but this time we execute the second line of code, the operation would be equivalent to:

a = b = 1
b = a+b = 1+1 = 2

Note how, this time, we first redefine the variable a and then update the variable b. This is where the discrepancy comes from.

Hope this helps! Keep up the good work!

Kind regards,
365 Hristina

Posted on:

01 Nov 2021

0

Got it, thanks!

Posted on:

30 Jun 2022

1

Could you please clarify this more? I do not quite understand Hristina's explanation?

Posted on:

09 Aug 2022

0

Elisha - this helped me to better understand:
Python Program to Print the Fibonacci Sequence (freecodecamp.org)

Submit an answer