Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Dungeon Game Random Choices

why doesn't my code work?

  • Create a function named nchoices() that takes an iterable and an integer. The function should return a list of nrandom items from the iterable where n is the integer. Duplicates are allowed.

my code:

def nchoices(iterable, n):
  n_list = []
  number = int(n)
  # get the random item from the list

#put n random items in the list
while number > 0:
  random_item = random.choice(iterable)
  n_list.append(random_item)
  number -=1

#return the list
return n_list

2 Answers

Jeff Morrison
Jeff Morrison
5,917 Points

What output are you getting, which you weren't expecting? From looking at your code:

  1. You need to import random in order to use it (which maybe you did and didn't copy and paste)
  2. Your while and return should be indented - otherwise they're not part of the function
  3. Instead of a while loop and decrementing (count n down) - I would use the range() function, which does the work for you. This is built in to do loop management for you.
import random
def nchoices(iterable, n):
    n_list = []
    for _ in range(n):
        ##do the choosing and appending here
    return n_list
AR Ehsan
AR Ehsan
7,912 Points

Here how I did it

import random
def nchoices(iterable, count):
    lst = []
    for x in range(count):
        lst.append(random.choice(iterable))
    return lst