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 LeeCourses Plus Student 593 Points
Help - 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
When 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' # 'T' 'Treehouse' # 'r' 'Treehouse' # 'e' 'Treehouse' # 'e' ... 'Treehouse' # 'e'
In 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]
hector alvarado15,784 Points
I 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