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

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