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

Whats wrong?

Hey folks,

I am stuck and don´t understand the error ... any help is highly appreciated.

My error is :

local variable 'count' referenced before assignment

My code:

count = 0
my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
my_list = ['apples', 'coconuts', 'grapes', 'strawberries']


def members(my_dict, my_list):
    for key in my_list:
        if key in my_dict:
            count =+ 1

    return count

count is assigned before the method call, why do I get this error?

Grigorij

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

I'm doing this from my iPad so I can't try it in a console, but just out of curiosity... What happens when you change

count =+ 1

To:

count += 1

Hey Jennifer,

thank you for a quick reply. I have done your suggestion and now I get this:

UnboundLocalError: local variable 'count' referenced before assignment

WEIRD

3 Answers

Try this:

#count = 0
my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
my_list = ['apples', 'coconuts', 'grapes', 'strawberries']


def members(my_dict, my_list):
    count = 0
    for key in my_list:
        if key in my_dict:
            count += 1
    print(count)
    return count

members(my_dict, my_list)

Very cool !!!

Thanks everyone !!!

I just ran your code and it was fine- no errors.

Yes Jennifer is right you should be incrementing count with +=. Make the switch and then try placing your 'count = 0' in your members() method towards the top and see if you get the results that you are expecting.