Python Python Basics (2015) Letter Game App Random Item

Cant figure out this challenge

whats wrong with my code?
import random

    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.