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 trialKirk Watts
2,202 PointsDid I misunderstand the challenge?
As far as I can tell, my code words and does what is asked of it, but I'm not sure I've properly understood what Kenneth wanted me to do?
As I see it, I expect an itterable (such as the word banana), get a random number between 0 and the length of the itterable -1 (in this case, it'd be between 0 and 5), then return the value of the index of the random number. So, if the random number turned out to be 3, we'd get the letter n back.
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item(iterable)
number = random.randint(0, len(iterable) - 1)
return iterable[number]
2 Answers
Jeff Wilton
16,646 PointsYou are missing a colon after your function definition,
def random_item(iterable):
but other than that, you are very close.
Indexes start at 0, so ''banana' would index like this:
[0=b, 1=a, 2=n, 3=a, 4=n, 5=a]
Thus 'banana'[3] is 'a' not 'n'.
This is why we go from 0 to the length of the word minus 1 (from 0 to 5 instead of 1-6).
Hope this helps!
Kirk Watts
2,202 PointsDoh! I'll try again. Didn't spot that missing colon :). Thanks!