Python if块中不支持的操作数类型TypeError

Python if块中不支持的操作数类型TypeError,python,python-2.7,for-loop,Python,Python 2.7,For Loop,我有一个函数以TypeError终止,我不确定原因: #under 4 million def fib(a, b): a, b = 0, 1 while b <= 4000000: a, b = b, (a+b) print a #always call it with "fib(0, 1)" fiblist = [fib(0, 1)] print fiblist #now for the function that finds the

我有一个函数以TypeError终止,我不确定原因:

#under 4 million

def fib(a, b):
    a, b = 0, 1
    while b <= 4000000:
        a, b = b, (a+b)
        print a

#always call it with "fib(0, 1)"

fiblist = [fib(0, 1)]
print fiblist
#now for the function that finds the sum of all even fib's

total = 0
for i in fiblist:
    if i%2 == 0:
        total = total + i
        print total
#不到400万
def fib(a,b):
a、 b=0,1
虽然b
fib(a,b)
不返回任何内容,但它会打印值,而不是返回值。如果函数没有表示返回任何内容,Python会隐式地使其
returnnone

因此,
fiblist=[fib(0,1)]
[None]

显然,
None%2
毫无意义


你应该重写fib(a,b)
作为一个生成器,并
产生它的结果。然后,您可以以类似于迭代
range()
xrange()
、列表等的方式对其进行迭代。

修复
fib
函数,使其返回一些内容。另外,请注意,您不必向其传递任何参数:

def fib():
    a, b = 0, 1
    lst = []
    while b <= 4000000:
        a, b = b, (a+b)
        lst.append(a)
    return lst
现在,
fiblist
将包含实际数字,您可以安全地对其进行迭代。这将修复您遇到的错误

def fib():
    a, b = 0, 1
    lst = []
    while b <= 4000000:
        a, b = b, (a+b)
        lst.append(a)
    return lst
fiblist = fib()