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 Basics (2015) Letter Game App Random Item

douglas gray
douglas gray
888 Points

any tips?

the instructions read "create a function named random_item that takes a single argument, an iterable. Then use random.randint() to get a random number between 0 and the length of the iterable, minus one. Return the iterable member that's at your random number's index. i've tried putting the random number in a variable and then getting the letter at that index, and i've tried using just one command with the random integer in it: "return Treehouse[random.randint] " and im not sure what else to do.

item.py
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

In your original post you say this: "'i've tried putting the random number in a variable and then getting the letter at that index". This would have been a correct way to do it and is how I came to the solution. I'm wondering if when you tried this technique if you managed to have some indentation error or something. It seems to me that your thought process was correct but there was some problem with the execution/writing of the code. Here's how I did it:

def random_item(treehouse_iterable):
  index = random.randint(0, len(treehouse_iterable)-1)
  return treehouse_iterable[index]

I defined random_item which takes an iterable from treehouse. Keep in mind that you don't get to decide what this iterable is. Treehouse is going to send information into your code to test it. So it needs to work for anything they possibly send. Then I made a variable named index to hold the random number that we generate. That random number needs to be between 0 and the length of the iterable they sent minus 1. This is because if they send in "hello" the length with be five. But because indexes start at 0 "h" will be at index 0. "e" will be at index 1 etc. The max index value on "hello" will be 4.
Then I simply return the item at the index we generated of the iterable sent by Treehouse. Hope this clarifies things!

edited for typos