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

How can I get rid of "UnboundLocalError: local variable 'retval_int' referenced before assignment" error message?

Hi,

I am trying to control whether retval_int and retval_str variables are defined so far by using if not retval_int and if not retval_str. But it did not work.

How can I solve this assignment?

instances.py
def combiner(the_list):

    for i in the_list:
        if isinstance(i, str):
            if not retval_str:
                retval_str = i
            else:
                retval_str = retval_str + i
        elif isinstance(i, int):
            if not retval_int:
                retval_int = i
            else:
                retval_int = retval_int + i
    return retval_str + str(retval_int)

1 Answer

I solved the problem in a different way:

def combiner(the_list):

str_list = [x for x in the_list if isinstance(x, str)] int_list = [x for x in the_list if isinstance(x, (int,float))]

return "".join(str_list) + str(sum(int_list))

print(combiner(["apple", 5.2, "dog", 8]))

Thanks!