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

Enzie Riddle
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Enzie Riddle
Front End Web Development Techdegree Graduate 19,278 Points

Index and rand.int

Here's the question:

You've seen how random.choice() works. It gets a random member from an iterable (like a list or a string). I want you to try and reproduce it yourself. 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. Check the file for an example.

I'm not sure where I am supposed to go with the index. Also if you could tell me what else I am doing wrong that'd be great :) Thanks!

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

import random
def random_item("Treehouse"):
    random.randint(0, len("Treehouse")) - 1
    return index()

1 Answer

Evan Trimby
Evan Trimby
5,381 Points

First, you don't want to put the string value as an argument to the function. If it did work it would always send the same value to the function. Use a variable name, you can use something descriptive like item_in or on a small function like this just a single letter. Second you find the index using the random.randint() method. Return the iterable "piece" at that location.