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 trialJames Gill
Courses Plus Student 34,936 PointsRandom selection not working?
Try as I might, The best error message I get is "where's nchoices()?" This looks like it should work, but maybe I'm missing something. Ideas?
Challenge: "Create a function that returns a list of random items from an iterable. The function, named nchoices(), should take an iterable and an integer for the number of items to return. Duplicates are allowed."
import random
def nchoices(iterable,num_items):
list = []
while len(list) < num_items:
item = random.choice(iterable)
list.append(item)
return list
3 Answers
Jason Anello
Courses Plus Student 94,610 PointsHi James,
I think all that you missed is that you didn't import the random module. Your code passes for me if I add that in.
You may want to use another name for your list
variable inside the function though since that's a built-in type.
Jason Anello
Courses Plus Student 94,610 PointsAlso, if you've been introduced to range
then you could set it up as for loop instead.
for _ in range(num_items):
James Gill
Courses Plus Student 34,936 PointsJason,
You're right--it worked. I "assumed" you never have to import modules when working in the code challenge editor, so it didn't even cross my mind. Live and learn.
Kenneth Love
Treehouse Guest TeacherYou really think I won't make you do all of the work? :) You don't know me well enough, then.
James Gill
Courses Plus Student 34,936 PointsYep, thought of range(). For some reason, the while loop seemed simpler to me.
James Gill
Courses Plus Student 34,936 PointsJames Gill
Courses Plus Student 34,936 Points(Edited to add the random module import.)