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 trialJustin 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
14,690 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
14,690 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,796 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