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

any tips?

i tried putting the random integer into a variable and then returning the letter at that index using the variable in it's place, and i tried making one line out of it (return treehouse[ random.randint] ). I'm not sure what else to do. i know it should only be a few lines.

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

1 Answer

Rick Buffington
Rick Buffington
8,146 Points

Okay, you are on the right track. Key items here:

  1. Import the random library
  2. Create a function called random_item with an argument that is iterable (ie. string)
  3. Return a random item from inside the iterable (using random.randint()) - between 0 and the length of iterable -1
import random

Now, we need to create the function - should be pretty straight forward, nothing tricky - argument can be named whatever, I just chose iterable because it was easier to remember.

def random_item(iterable):

And here is where it gets a little hairy. They want you to use random.randint() and the docs around that are that it takes 2 arguments: the first argument is the starting number, and the 2nd is the highest number to use. We know from the notes that the lowest number is 0 and the highest number should be the length of your iterable -1. That should give you the 2 values to look through. To get the length of a string, we use:

len(iterable)

And the random.randint

random.randint(LOW VALUE, HIGH VALUE)

That will give us an integer with the length of the string. The reason they want you to subtract 1 is because of the fact that the index of the string starts at 0.

The last part is to return the item from within your iterable. You are on the right track with your index return, you just need to fix your random.randint syntax.

return iterable[YOUR RANDOM GENERATOR GOES HERE]

If you need further help let me know.