Iterating through the Fibonacci sequence
<p>so i'd like to iterate through the Fibonacci sequence (but this could apply to any non-arithmetic sequence). i've written a function fibonacci:</p>

<pre><code>from math import sqrt
def F(n):
    return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
</code></pre>

<p>which returns the fibonacci number for any given input. this bit seems to work OK. However, I'd like to include a couple of conditions, like even numbers and F(n) below a certain limit. I tried using an if loop like this:</p>

<pre><code>def ser():
    count = 0
    for i in F(n):
        if F(n) &lt;= 4000000 and F(n) % 2 == 0:
            count = count + F(n)
</code></pre>

<p>But it seems like you can't use F(n) in the iteration for loop like I did. I'm a complete novice at python, so how would be best to use the F(n) function I created to iterate over the sequence? Thanks</p>

<p>What is the range of <code>n</code> that you are looking to run the fibonacci number on?<br>
Your definition of fibonacci is in a closed form, so you need to give each number you want to calculate:</p>

<pre><code>import itertools
count = 0
for n in itertools.count(1):
    if F(n) &gt; 4000000:
        break
    if F(n) % 2 == 0:
        count += F(n)
</code></pre>

<p>You can use a generator form of fibonacci and use <code>itertools.takewhile()</code> to limit the output:</p>

<pre><code>def F():
    a,b = 0,1
    yield b
    while True:
        a, b = b, a + b
        yield b

count = sum(f for f in it.takewhile(lambda x: x &lt;= 4000000, F()) if f % 2 == 0)
</code></pre>

python iteration sequences