Python中Fibonacci序列中的和偶数

时间:2016-05-26 05:50:32

标签: python fibonacci

我是一名使用Python 3的新程序员,我并不确定如何修复此代码。我试图从fib序列中打印所有偶数值的总和,只要它们在值n之下。我可以得到fib序列,只是添加偶数值。

def even_fibonacci(n):
    total = 0
    a, b =  0, 1
    while b < n:
        a, b = b, a+b
        return sum([b if b % 2 == 0])

even_fibonacci(100)

1 个答案:

答案 0 :(得分:-1)

def even_fibonacci(n):
    total = 0
    a, b =  0, 1
    sum = 0 # default, as 0 is even
    while b < n:
        a, b = b, a+b
        if b%2 == 0:
            sum += b # keep adding b if it is even
    return sum

sum = even_fibonacci(100)
print(sum)
相关问题