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

Enguerrand Harmel
Enguerrand Harmel
1,242 Points

I don't understand.

I don't understand why my code is wrong.

item.py
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item(arg[])
  index = random.randint(0, len(arg[])
  return arg[index]      

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

There's a couple of problems here. First you're missing the colon after the definition of your function. Secondly, your square brackets after the arg is not needed until the return line. The thing going into the arg is already an array so no need to put the brackets there. Same thing where you have the index equals. The name arg refers to the entirety of the array. Finally, we want a number between 0 and the length of arg minus 1. In your code it's possible that you'll get a number that is the length of the array which will result in some kind of out of bounds error when you try to access an element outside the array. Take a look at how I did it:

import random
def random_item(arg):
  index = random.randint(0, len(arg)-1)
  return arg[index]     

edited because I forgot 2 words