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 trialAndrei Oprescu
9,547 Pointscan you tell me why my code is not doing the right thing?
I have a code:
import random
def random_item(astring): random_item = random.randint(0, len(astring)) return random_item
Can you please look at the question of the exercise and tell me what I did wrong?
Thanks
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item(astring):
random_item = random.randint(0, len(astring))
return random_item
2 Answers
Niko Klanecek
3,152 PointsFirst, your indentation doesn't match, return
should be on the same level as the previous line.
Also you're just returning a random number between 0 and the len
gth of the string. You need to instead return the letter at that index. Try something like return astring[random.randint(0, len(astring) - 1)]
I did -1 on the len
of astring
because the last number would otherwise be out of range, since we start counting from 0.
Andrei Oprescu
9,547 PointsThank you! I completely forgot that I had to tell the program to search the number in the argument.
Thanks
Niko Klanecek
3,152 PointsNiko Klanecek
3,152 PointsIf you want to reuse your code you could do