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 trialManu C.
Courses Plus Student 10,265 PointsAnswer Quiz Random
What am I doing wrong ?
Why is the following code working and the one I use in the challenge window (item.py) not working ?
Thank you very much,
import random
iterable = input("Choose an iterable : ")
def random_item(iterable): long_iter = len(iterable) print("long_iter: {}".format(long_iter)) rand_nr = random.randint(1, long_iter - 1) print("rand_nr: {}".format(rand_nr))
print(iterable[rand_nr])
random_item(iterable)
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item(iterable):
long_iter = len(iterable)
rand_nr = random.randint(1, long_iter - 1)
return iterable[rand_nr]
1 Answer
Tri Pham
18,671 PointsRead the comments again. "Treehouse" was the input and 4 was selected and that resulted in h being returned. That means they are assuming you start at 0 not 1. Otherwise, "T" would never be returned.