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 trialMalcolm Robertson
8,478 PointsCorrect Answer outside def, what am I doing wrong?
Hi,
Reference Challenge 1 of 1 Dictionaries Membership
I must be having issues understanding functions, the layout and rules on calling them.
I can run the below code and get the answer to to the challenge but when I try to put the code into a def I get errors.
Code outside a def
my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
my_list = ['apples', 'coconuts', 'grapes', 'strawberries']
for name in my_dict and my_list:
if name in my_dict and my_list:
print(name)
else:
print("Else Print")
break
When I put the above into a def as below I get a error (Bummer! Expected 2, got apples.):
def members(adict, alist):
my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
my_list = ['apples', 'coconuts', 'grapes', 'strawberries']
for name in my_dict and my_list:
if name in my_dict and my_list:
print(name)
return(name)
else:
print("Else Print")
continue
members(my_dict, my_list)
Any help would be much appreciated.
Malcolm Robertson
8,478 PointsJennifer, I removed the return(name) and I am now getting Bummer! Try again!
I presume this approach I am taking is not valid.
1 Answer
Idan Melamed
16,285 PointsHi Malcolm
I've noticed a few things:
- The challenge asks you to count and return how many times the items in the list are also keys in the dictionary.
- You don't need to assign my_list and my_dict
- You also don't need to call the function
- I would try to change the for loop and if statement to check only in one variable. For example, my for loop would be: for word in my_list:
If you want to see a solution, you can check out this link: https://trinket.io/python/a803c750e9
Malcolm Robertson
8,478 PointsHi Idan,
I see what you mean.
Thanks for your help.
Jennifer Nordell
Treehouse TeacherJennifer Nordell
Treehouse TeacherTry removing this line and see what happens:
return(name)
This would explain why you're returning apples instead of 2.