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!
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 trial
Ashmit Pathak4,441 Points
CAN'T FIND THE WAY TO DO IT . PLEASE HELP
I don't know how the code will look like for this plz help me with your code
# EXAMPLE # random_item("Treehouse") # The randomly selected number is 4. # The return value would be "h" import random random_item = random.randint(0 , len())
Alexander Davison65,469 Points
You are on the right track! Just remember:
- The code you're writing (except the
randomimport) goes inside of a function called
lenfunction takes a single iterable. You simply pass in the iterable passed into
- Don't forget to subtract the length by one! Computers start counting at zero, so the last element is at the size of the list minus one.
With all of this in mind, you may write this:
PLEASE DO NOT COPY-AND-PASTE. Trust me, just read this code, and reproduce this code yourself. It's the best way to learn to code!
import random def random_item(iterable): return iterable[random.randint(0, len(iterable) - 1)]
Happy coding! ~Alex