python-workout icon indicating copy to clipboard operation
python-workout copied to clipboard

Unsupported operand type(s) for +: 'int' and 'str'

Open jan-nemec opened this issue 4 years ago • 3 comments

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.

jan-nemec avatar Feb 08 '21 21:02 jan-nemec

one_item should be int(one_item) IMO.

jimmy605 avatar Mar 14 '21 02:03 jimmy605

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))

aj-white avatar Mar 31 '21 12:03 aj-white

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!

LittleDeuce avatar Feb 21 '23 02:02 LittleDeuce