I have a function which is terminating with a TypeError and I'm not sure why:
#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
here is the error message:
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'
>>>
I appreciate any help you may provide. thanks.
Patashu :
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.\n\nTherefore, fiblist = [fib(0, 1)] is [None].\n\nClearly, None%2 is meaningless.\n\nYou 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