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

Cant figure out this challenge

whats wrong with my code?

item.py
import random

random_item(i):
    random.randint(0,len(i)-1)
    return i

1 Answer

Well, there are several problems with your code.

First, you missed def keyword when defining a function:

def random_item(i):
    ...

Second, according to the instruction, you need to:

Return the iterable member that's at your random number's index.

So there are a couple of things you need to finish.

  • You've generated a random number, but it wasn't assigned to any variable. I would assign it to a variable called random_index, since that's what it is.
def random_item(i):
    random_index = random.randint(0,len(i)-1)
    ....
  • You need to "return the iterable member" at random_index. This is fairly easy to do:
def random_item(i):
    random_index = random.randint(0,len(i)-1)
    return i[random_index]

One last comment: I would name the parameter iterable or something more descriptive, rather than a single letter i to make it more readable. Take some time and read PEP8. It will help you write more structured and readable code.

with your code i still get A name error message that random item is not defined

That is odd. I passed the challenge with the exact code. Did you do import random? A NameError of random_item would imply that the random_item function is not defined at all. If the error still persists, can you copy and paste your workspace here?

If the original problem was solved, a "best answer" would be appreciated. Good luck on learning.