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

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!

item.py
import random

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







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

1 Answer

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 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.

Cheers

Alex