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 trialMoses Ong
889 PointsI've gotten the right answer on another text-editor. I'm not sure why I was fault here.
I'm not sure whether I've understood the question correctly.
From my understanding, we're required to
Generate a random number based on the length of our iterable
Based on the generated number, be able to output the string alphabet of the "index"
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item(input):
random_num = random.randint(0,8)
input = "Treehouse"
random_string = input[random_num]
print(random_string)
random_item(1)
2 Answers
Boban Talevski
24,793 PointsThere are several issues with the code you have.
You should not assign a value to the input variable, it's something that will be sent in to the function and your code needs to handle it in general terms. That is, get a random number between 0 and the length of input(whatever its value is, you shouldn't care), and use that random number as an index to return an item from the input variable.
The important part is to return the item, not print it, which is the other issue with your code.
Here is a simple one line solution
def random_item(input):
return input[random.randint(0, len(input))]
Moses Ong
889 PointsThank you. You've definitely pointed me in the right direction.
Ever grateful m8!
Boban Talevski
24,793 PointsGlad to help. You could mark my answer as best answer so the problem can be treated as solved. ;)