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

CAN'T FIND THE WAY TO DO IT . PLEASE HELP

I don't know how the code will look like for this plz help me with your code

item.py
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
random_item =  random.randint(0 , len())

1 Answer

Hello Ashmit,

You are on the right track! Just remember:

  • The code you're writing (except the random import) goes inside of a function called random_item.
  • The len function takes a single iterable. You simply pass in the iterable passed into random_item.
  • Don't forget to subtract the length by one! Computers start counting at zero, so the last element is at the size of the list minus one.

With all of this in mind, you may write this:

PLEASE DO NOT COPY-AND-PASTE. Trust me, just read this code, and reproduce this code yourself. It's the best way to learn to code!

import random

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

Happy coding! :zap: ~Alex