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

Jonathan Camacho
Jonathan Camacho
1,504 Points

How is this incorrect?

"First, import the random library. Then create a function named random_item that takes a single argument, an iterable. Then use random.randint() to get a random number between 0 and the length of the iterable, minus one. Return the iterable member that's at your random number's index"

Those are my instructions, and I believe I followed them correctly; however, it says that the name "random_item" is not defined. I dont understand, because it is a function that I am currently defining, please help.

item.py
import random

numbers = (0, len(ite))-1
item_list = list(ite)

def random_item(ite):
    return item_list[random.randint(numbers)] 

1 Answer

Jaxon Gonzales
Jaxon Gonzales
3,562 Points

Hi Jonathan!

The thing about this code challenge is that it is possible to do it all inside the function (other than the import of course). It would go something like this:

import random

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

Things to note:

  1. No need to turn the utterable into a list, you can return something based on an index in a string. For example the letter at index 3 of the word "Blanket" would be "n"
  2. There is no need to create a range for the random.randint method. You enter the range in the parentheses when you call the method.