Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Question about the sum of Fibonacci numbers implemented in Python

Hi, I have a question, assuming I have a task to find a sum of all even Fibonacci numbers below 4000 I have written the following code:

def fibSequence(a, b, sum, target):
    c = a + b;
    print c
    a = b
    b = c
    if c % 2 == 0:
        sum += c
        print 'I am new sum ' + str(sum)
    if c < target:
        fibSequence(a, b, sum, target)
    return sum

print 'The sum is: ' + str(fibSequence(1, 1, 0, 4000))

which produces the following output:

2
I am new sum 2
3
5
8
I am new sum 10
13
21
34
I am new sum 44
55
89
144
I am new sum 188
233
377
610
I am new sum 798
987
1597
2584
I am new sum 3382
4181
The sum is: 2

As you can see while the sum variable is actually updating the final one that is being returned is still equal to 2. Can anyone please provide a reasonable explanation to this?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

Your code works as it's calling down the recursive chain, but doesn't pass results back up the chain.

Try assigning the fibSequence return value to sum

    if c < target:
        sum = fibSequence(a, b, sum, target)
    return sum

Small, yet important thing I consistently overlooked. Thanks for pointing it out!