猿问

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

我有一个以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

这是错误消息:


Traceback (most recent call last):

  File "C:\Python27\ProjectEuler\ProjectEuler2.py", line 19, in <module>

    if i%2 == 0:

TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'

>>> 


慕尼黑5688855
浏览 253回答 2
2回答

慕仙森

修复fib函数,使其返回某些内容。另外,请注意,您不必向其传递任何参数:def fib():&nbsp; &nbsp; a, b = 0, 1&nbsp; &nbsp; lst = []&nbsp; &nbsp; while b <= 4000000:&nbsp; &nbsp; &nbsp; &nbsp; a, b = b, (a+b)&nbsp; &nbsp; &nbsp; &nbsp; lst.append(a)&nbsp; &nbsp; return lst还要修复此行:fiblist = fib()现在fiblist将包含实际数字,您可以安全地对其进行迭代。这样可以解决您遇到的错误!
随时随地看视频慕课网APP

相关分类

Python
我要回答