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 Python Collections (Retired) Dungeon Game Random Choices

Hi There, I think I've got it correct (using python outside of workspaces to run the code), but it says try again.

Code that I have is, (sorry for the terrible variable naming, was trying different names to see if that made a difference):

iterable = [1,2,3,4,5,6,7,8,9]  
integer = 4  


def nchoices(twoname,onename):  
     mlist = list()   
     count = onename  
     while count > 0:  
       count -= 1  
       mlist.append(random.choice(twoname))  
       continue  
    return(mlist)  


nchoices(iterable,integer)

NB. Indentation doesn't seem to be working when using the comments.

3 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

So trying your exact code up there locally, I get an NameError that random isn't defined, so make sure you have the import.

Once I import random, though, the code works and get me 4 items from the iterable.

Your code has some strange design decisions, from the Python side, but it's code that works. If you want, I'm happy to go through what I see as being "unPythonic" code.

Hi Kenneth,

Thanks for the answer. Yes if you do have the time please let me know with regards to python style coding. I do a sort of hack mix and match.

Thanks for the Answer Cheers Anthony

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

OK. Here goes:

  • The continue is unnecessary. Since it's reached the end of the loop, it'll continue anyway.
  • The count and onename stuff is pretty unnecessary, too, since you can just loop through the contents of a list (for x in y:) and you can make that list using range().
  • return isn't a function, so you don't need to have parentheses. I can't think of a situation where it should ever matter, though.

To rewrite your code, I'd write it like this:

iterable = [1,2,3,4,5,6,7,8,9]  
integer = 4  


def nchoices(iter, num):  
     mlist = list()
     for step in range(num):
          mlist.append(random.choice(iter))  
     return mlist

nchoices(iterable,integer)

Cheers Kenneth,

Much appreciated -Anthony