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

Python nchoices(): function problem help? Thank you!

I feel like this should be working, and from the best of my current abilities this is about all I can do. What is wrong?

choices.py
def nchoices(iterable, integer):
  random_item = []
  import random
  for index in range(int(integer)):
    tup = random.chose(iterable)
    random_item.append(tup)
  return random_item

2 Answers

Ryan Ruscett
Ryan Ruscett
23,309 Points

Hola,

Hey, you had the right idea. I used a while loop for it's a bit more practical at least for me. Much less confusing to read too.

The imports should always go at the top of your program as well.

import random

def nchoices(iterable, integer):  
  counter = integer           ========= 1
  random_item = []          ========= 2
  while counter > 0:          =========3
    value = random.choice(iterable) =4
    random_item.append(value) 
    counter = counter -1                     =5
  return random_item                      =6
  1. I take integer and I change it to counter. For this is some number of random items from the iterable that I need.

  2. Than I create an empty list.

  3. Then I say while counter is bigger than 0. Since I don't care what counter is.

  4. Than I saw value = randomly choose an item from the iterable with random.choice. So that was correct. Good work there. Then add it to my list

  5. Then I count the counter down by 1

  6. Once the counter is 0 I stop and return the random_list.

Let me know if this clears it up for you or if you have additional questions.

Thank you so much! Makes way more sense now!