Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Justin Lee
Courses Plus Student 593 PointsHelp - Random item
Not sure what's wrong.
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item(treehouse):
answer = random.randint(0, len(treehouse) -1):
return answer
3 Answers

rainmaker
13,934 PointsWhen we define the function random_item we are expecting a string to be used as an argument. Remember characters in strings can be accessed by their index beginning at 0. For example, in the string 'Treehouse' the 0th index is 'T' while the last character 'e', is the 8th index . Then we define the variable random_index it chooses a random integer between 0-8 (len(string)-1). Finally, we return the character at the random_index with string[random_index].
I hope this is clear as I am still learning myself.
def random_item(string):
random_index = random.randint(0, len(string) - 1)
return string[random_index]
'Treehouse'[0] # 'T'
'Treehouse'[1] # 'r'
'Treehouse'[2] # 'e'
'Treehouse'[3] # 'e'
...
'Treehouse'[8] # 'e'

rainmaker
13,934 PointsIn your code you are only returning a random index within the length of the paramater(treehouse).
def random_item(string):
random_index = random.randint(0, len(string) - 1)
return string[random_index]

Justin Lee
Courses Plus Student 593 PointsI don't quite get it. Can you please explain?

hector alvarado
15,784 PointsI think the problem is the ":" on the statment, and the indentation of the return statement, remember keep the same indentation per block.
def random_item(treehouse):
answer = random.randint(0, len(treehouse) -1)
return answer
Justin Lee
Courses Plus Student 593 PointsJustin Lee
Courses Plus Student 593 Pointsthanks man