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
Grigorij Schleifer
10,365 PointsWhats 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
Grigorij Schleifer
10,365 PointsHey 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
Jeremy Hill
29,567 PointsTry 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)
Grigorij Schleifer
10,365 PointsVery cool !!!
Thanks everyone !!!
Jeremy Hill
29,567 PointsI just ran your code and it was fine- no errors.
Jeremy Hill
29,567 PointsYes 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.
Jennifer Nordell
Treehouse TeacherJennifer Nordell
Treehouse TeacherI'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 =+ 1To:
count += 1