Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (2015) Letter Game App Random Item

Jamal Scott
Jamal Scott
9,656 Points

Python

Cant seem to get this one right, i have this so far

EXAMPLE

import random

random_item("Treehouse")

def random_item("Treehouse"): num = random.randint(0, len("Treehouse")-1) letter = [num] return letter

The randomly selected number is 4.

The return value would be "h"

Many thanks

item.py
# EXAMPLE

import random

# random_item("Treehouse")
def random_item("Treehouse"):
  num = random.randint(0, len("Treehouse")-1)
  letter = [num]
  return letter

# The randomly selected number is 4.
# The return value would be "h"

1 Answer

Hi Jamal,

The parameter of your function is a string, where it should be a variable. Your letter variable is a list with one item in it, which is the random integer created, instead of being the random letter; if you pushed all your code into one line, skipping the variable assignment and putting that code into the index for the iterable input of your function, it will pass and will be more efficient;

import random

def random_item(iterable):
  return iterable[random.randint(0, len(iterable)-1)]

Please let me know if you have any questions about how or why that works!

The function isn't being used in this example, so the iterable parameter isn't anything yet - it's a placeholder variable. However, iterable would be a string that you provide. So for example,

random_item("catfish")

would return a random letter of "catfish".