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

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?