0

A tutorial I am going through had the following program

# This program calculates the Fibonacci sequence
a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
    count = count + 1
    old_a = a    # we need to keep track of a since we change it
    print(old_a,end=" ")   # Notice the magic end=" " in the print function arguments that
                           # keeps it from creating a new line
    a = b
    b = old_a + b
print() # gets a new (empty) line

The code is perfect. However, I am not able to figure out how the sequence is calculated. How are the values changed to create the sequence?

cfi
  • 10,372
  • 7
  • 54
  • 97
  • Your code formatting is broken. Good [Fibonacci related questions](http://stackoverflow.com/a/499245/923794) are already aplenty on this site. Getting your code explained or discussed is not a good question format for this site. Please read at least the first two paragraphs of [the FAQ](http://stackoverflow.com/faq). – cfi Mar 25 '13 at 13:48

2 Answers2

0

It'll make more sense if you remove all of that extraneous code:

while count < max_count:
    old_a = a
    a = b
    b = old_a + b

The old_a is probably confusing you. It's the long way of writing this:

a, b = b, a + b

Which swaps a with b and (at the same time), b with a + b. Note that it isn't the same as writing:

a = b
b = a + b

Because by the time you re-define b, a already holds its new value, which is equal to b.

I'd also run through the code manually by writing it out on paper.

Blender
  • 275,078
  • 51
  • 420
  • 480
0

This code works fine:

a, b = 0, 1
for _ in range(20):
        print a
        a, b = b, a+b
Asclepius
  • 49,954
  • 14
  • 144
  • 128
e.arbitrio
  • 476
  • 4
  • 14