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

Frank Sherlotti
PLUS
Frank Sherlotti
Courses Plus Student 1,952 Points

Random choices challenge: How do I get my loop to stop at a certain integer?

Create a function named nchoices() that takes an iterable and an integer. The function should return a list of n random items from the iterable where n is the integer. Duplicates are allowed. --- I think my code so far does what it's asking me to do but I just can't quite figure out how to make it stop at a certain spot. Any help would be greatly appreciated. THANKS!

choices.py
def nchoices(thing, num):
  x = []
  import random
  for item in thing:
    random.choice(thing)
    x.append(thing)
  return x

1 Answer

leong shing chew
leong shing chew
5,618 Points
def nchoices(thing, num):
  x = []
  count=0
  import random
  while (count < num):
    random.choice(thing)
    x.append(thing)
    count = count +1
  return x

How about using a while loop rather than a for loop?