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

how would i do the random

ok i have not used random keywords in forever i was wondering how i would do this properly

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

import random

def random_item("Treehouse"):
    return random_item("Treehouse").index(random.randint(0, len(random_item - 1))
Michael Barlow
Michael Barlow
34,317 Points

In the function definition, you first want to make sure you're passing in a variable as an argument:

def random_item(my_string_arg):

For getting the item, you can use the randint() or the sample() function. You're really close on the former but since Python doesn't have an index() function:

    return my_string_arg[random.randint(0, len(my_string_arg) - 1)]

Since sample() returns a list, you can also do the following:

    return random.sample(my_string_arg, 1)[0]

"Treehouse" needs to be brought in as an argument when you call the function. In Python, strings are easily used like arrays so, "Treehouse"[0] would be "T" in your example. This will demonstrate what you're trying to do:

import random

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

print(random_item("treehouse"))

or if you don't want to pass through an arg:

import random

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

print(random_item())