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

Idan shami
Idan shami
13,251 Points

random item

I stuck in this challenge... I don't know what to do please help

thank you.

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

1 Answer

Hey Idan,

so far you are doing great. Now you have to make a random number that is between 0 and the length of the "arg" argument you passed to your function. You can create a new variable for that, I'll call it "num".

num = random.randint(0, len(arg) -1)

That code will give you a random number. Now, remember that strings are iterable, so you can call any letter of any string by it's index using String[index]. Here is how it works;

my_name = "Eric"
print(my_name[0]) # This will print out the letter E (remember that the first item is 0 indexed)
your_name = "Idan"
print(your_name[2]) # This will print out the letter U

So your code would look something like this:

import random

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