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 trial

Python Python Basics (2015) Letter Game App Random Item

What 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.

item.py
# 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
Daniel Vargas
29,184 Points

Hello

Well there are few things you could improve:

  1. You don't need to ask for the iterable with an input() since the method is receiving the variable.
  2. You shouldn't create a list with the iterable since it is already an iterable object.
  3. 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]

Thanks for the advice!

Oszkár Fehér
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Oszkár Fehér
Treehouse Project Reviewer

Hi 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

Thanks for the help! I will take all the advice i can get.