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

confused on how the random_item is supposed to look

I've been over this like 9 times trying to understand what the argument is supposed to be, if i put in iter it just seems to confuse the output, what am I missing here? What step is not being implemented? or am I just completely misunderstanding this task all together?

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

import random

def random_item(str):
    iterable_minus_1 = len(str) - 1
    random_num = random.randomint(0, iterable_minus_1)
    return index(random_num)

5 Answers

olegovich7
olegovich7
6,605 Points
import random

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

This works. One more mistake i found: your function takes 'str' as argument, and that's a reserved name!

olegovich7
olegovich7
6,605 Points

Hi Byron! It's your last line. It's not just index(), its str.index(). And this actually returns you index of an object you give it as an argument, and you need vice versa

return str[random_num]

ooooohhhhhhh, my brain was on fire trying to figure this out lol, thanks so much.

I tried what you said, but still not taking this for an answer. I'm even more confused than i was :( this is the message it gave me "TypeError: descriptor 'index' requires a 'str' object but received a 'int'" which im guessing the rand_num variable is passing an integer, but not returning something it can scan.....

man i found this literally 10 seconds before i got the notification haha! i solved it but using

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

i also figured out why this works and mine didn't, i was over thinking it waay too much