Python Python Basics (2015) Letter Game App Random Item

Hey, I've trouble understanding this question. I've tried a couple of times and rewatched the video

Couldn't quite wrap my head around this. Need some help!
import random

def random_item(treehouse):
    random_num = random.randint(0,8)
    return random_num 

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

1 Answer

Alex Koumparos
Alex Koumparos
Python Web Development Techdegree Student 35,870 Points

Hi Moses,

Let's take a look at the task specifications and compare it to the code. The question says we are going to reimplement the random.choice() method. Let's think about how that works: we pass it some kind of iterable and it will give us back a random element from the iterable. So, we'll know we've answered the question when we've created a function into which we can pass an iterable and get back a random element from the iterable.

What do we get when we pass an iterable, say 'hello' into your function?

First we get a random number and put it in the random_num variable. In your case, we are going to get a random number between 0 and 8. That's perfect if the iterable we passed into the function had exactly 9 elements, but for this function to have the same behaviour as random.choice() it has to work with iterables of a length that isn't just 9. If we passed in 'hello' there's a 4 in 9 chance that we'll get an out of bounds error. Therefore, instead of hardcoding 8, we want to give randint a value that is the length of the iterable (which we called treehouse). What function returns the length of an iterable?

Next we want to use the random number we got in the previous line as the index value to pick the random element from the iterable. Right now you're just returning the random number. Let's say the random number was 4, we'd want to return the letter 'o' (the element in 'hello' with the index value 4) but you're returning 4. How do we get an element from an iterable when we know the index value?

Hope these hints help you out,

Let me know if you're still confused.