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 trialTimothy Delahanty
3,057 PointsWhat am I missing or not doing correctly?
Can anyone give me a hint as to what I am doing incorrectly? I have tried several variations but the code does not seem to want to work for me.
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item(iterable):
iterable=input("What do you need: ")
list_iterable=list(iterable)
random_number=random.randint(0,len(list_iterable)-1)
return(iterable[random_number])
2 Answers
Daniel Vargas
29,184 PointsHello
Well there are few things you could improve:
- You don't need to ask for the iterable with an input() since the method is receiving the variable.
- You shouldn't create a list with the iterable since it is already an iterable object.
- You should substract 1 to the random number, not to the length itself.
I hope that can help you.
import random
def random_item(it):
ran = random.randint(0, len(it)) - 1
return it[ran]
Oszkár Fehér
Treehouse Project ReviewerHi Timothy Eventuallu your code will return the correct value there is just some things in plus
iterable=input("What do you need: ")
list_iterable=list(iterable)
You don't need an input and the iterable it's already a list, you don't need to make it a list The indentantion on the return it's not correct, make sure that you indent correctly The code it should look like this
def random_item(iterable):
random_number = random.randint(0,len(iterable) - 1)
return(iterable[random_number])
For best practice try to use the whitespaces where it's needed ex
random_number = random.randint(0, len(iterable) - 1)
I hope this will help you out Happy coding
Timothy Delahanty
3,057 PointsThanks for the help! I will take all the advice i can get.
Timothy Delahanty
3,057 PointsTimothy Delahanty
3,057 PointsThanks for the advice!