Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Object Oriented Python Combiner Question

Question: Alright, here's a fun task! Create a function named combiner that takes a single argument, which will be a list made up of strings and numbers. Return a single string that is a combination of all of the strings in the list and then the sum of all of the numbers. For example, with the input ["apple", 5.2, "dog", 8], combiner would return "appledog13.2". Be sure to use isinstance to solve this as I might try to trick you.

Error: Didn't get the expected output.

I tried my code in my local editor with the inputs provided in the question and got the correct output. The question wants me to use isinstance(), but I thought I got around that by using type(). What did I do wrong?

instances.py
def combiner(my_list):
    words = []
    nums = []
    for item in my_list:
        if type(item) == int or type(item) == float:
            nums.append(item)
        elif type(item) == str:
            words.append(item)
    output = str("".join(words))
    my_sum = 0
    for num in nums:
        my_sum += num
    output += str(my_sum)
    return output

2 Answers

If you use the example list ['apple', 5.2, 'banana', 8] they gave you for the code you have here, yes, your code will work just fine. However, since the instructions say "I might try to trick you," there's probably a test for your code that intentionally tries to trip you up using TYPE. TYPE and ISINSTANCE work differently in that ISINSTANCE will recognize subclasses as members of their base classes whereas TYPE does not. So I'm assuming that one of the tests uses a subclass of float, int, or str, causing TYPE to throw an error whereas ISINSTANCE recognizes the inheritance from the base classes.

Thank you. It worked. The only thing is that if they put a True in the list, it would increment the sum by one since Booleans are a subclass of ints. That is what threw me off.

Alright, here's a fun task!

Create a function named combiner that takes a single argument, which will be a list made up of strings and numbers.

Return a single string that is a combination of all of the strings in the list and then the sum of all of the numbers. For example, with the input ["apple", 5.2, "dog", 8], combiner would return "appledog13.2". Be sure to use isinstance to solve this as I might try to trick you.

guys help