python-workout
python-workout copied to clipboard
Unsupported operand type(s) for +: 'int' and 'str'
https://github.com/reuven/python-workout/blob/d9ec04ca47aa92fa5d013610dd3bd0dbf8903a8f/ch01-numbers/e02b4_sum_intable.py#L20
If I run the function sum_intable() with the input list ['1', '2', '3'] the function will return the TypeError. The is_intable function returns True for each of these input elements.
one_item should be int(one_item) IMO.
Yes, I agree with @jimmy605, when you pass "2" to is_intable function, int() will convert it's type from 'str' to 'int' so is_intable() returns True. However in sum_intable() it remains a string so summing a 'str' and an 'int' throws a TypeError. The return of sum_intable() should be
return sum(int(one_item) for one_item in items if is_intable(one_item))
This issue gave me a lot of trouble. The is_intable fuction returned False when I added '2' but threw a TypeError when I called sum_intable. I never thought I'd have to put int in the return statement. Thanks!