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

justinploeger
justinploeger
1,878 Points

random_item code

I never understand why these 'tests' reject my code. It works exactly as it is supposed to, per the instructions. I test ran it in the workspace, and it works perfectly. What am I missing?

item.py
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"

import random

alpha = ('apple', 'banana', 'orange', 'grape')

def random_item(alpha):
    rand = random.randint(0,len(alpha))
    print(alpha[int(rand)])

random_item(alpha)

2 Answers

Ari Misha
Ari Misha
19,323 Points

Hiya Justin! You do have a few issues with your code.

  • First off, You're doing too many stuff. Try to keep your code clean , simple and concise.

  • Secondly, Challenge asked you to produce a random number between 0 and "len(alpha)-1", not "len(alpha)". Even if challenge doesnt ask you to reduce a number from "len(alpha)", you're still gonna have to do the same procedure coz list index begins with "0".

  • Thirdly, you dont have to convert "rand" variable to "int". But i like it coz you're being cautious and thats a good sign.

  • And you're printing your result instead of "returning" it.

So yeah i cleaned your code a bit and made it all simple and concise:

import random

def random_item(alpha):
    rand = random.randint(0, len(alpha)-1)
    return(alpha[rand])
Sachin Kanchan
Sachin Kanchan
564 Points

I did it like this

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

if you are unsure or confused, make variables, assign values and call them wherever necessary. Now once you run it in workspace and are confident it works, just remove the variables and use raw values and enter into the code challenge.