There are several problems in your code:
- You loop four million times instead of the condition being true.
- You repeated the code in the body of the loop.
Most people, when they start learning Python, only study imperative programming. This is not surprising because Python is a required language. But Python also supports functional programming to some extent, and for this kind of exercise, the functional programming approach is more enlightened, in my opinion.
First, define a generator that generates all Fibonacci numbers:
def fib(): a = b = 1 while True: yield a a, b = b, a + b
To use this generator, we can import some useful functions from itertools. To print the first few numbers, use islice :
from itertools import ifilter, islice, takewhile for x in islice(fib(), 5): print x
one
one
2
3
5
To find only even numbers, we can use ifilter to create a new generator:
def is_even(x): return x % 2 == 0 evenfibs = ifilter(is_even, fib()) for x in islice(evenfibs, 5): print x
2
8
34
144
610
To get numbers from a generator while the number is more than four million, use takewhile :
for x in takewhile(lambda x: x < 4000000, evenfibs): print x
To solve the problem, you can use the amount:
sum(list(takewhile(lambda x: x < 4000000, evenfibs)))
Hopefully this shows that the functional programming approach is not complicated and is a more elegant way to solve certain problems.