3

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

感谢您提供的任何帮助。谢谢。

4

2 回答 2

4

fib(a, b) does not return anything - instead of returning a value, it prints it. If a function does not say to return anything, Python makes it return None implicitly.

Therefore, fiblist = [fib(0, 1)] is [None].

Clearly, None%2 is meaningless.

You should rewrite fib(a, b) to be a generator and to yield its results. Then you can iterate over it, in a similar fashion to iterating over range(), xrange(), lists and so on.

于 2013-06-14T03:15:26.030 回答
4

Fix the fib function, make it return something. Also, notice that you don't have to pass any parameters to it:

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

Also fix this line:

fiblist = fib()

Now fiblist will contain actual numbers, and you can safely iterate over it. That'll fix the error you were experiencing!

于 2013-06-14T03:15:30.823 回答