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

Greg Isaacson
PLUS
Greg Isaacson
Courses Plus Student 702 Points

I Dont understand the question

Hi Guys!

I just did the previous tutorial and I understand everything fine!!

But now I get this question and I dont get it...

The question is asking for me to create a function that will select a random number...

so I create my function like this:

def random_item(): random.randint ()

so this selects a random integer...

then what? How do I minus one from it??

It says :

"get a random number between 0 and the length of the iterable, minus one"

I dont understand... "And the length of the iterable, minus one" I must do what, get a random number AND get the length of the iterable minus one????

item.py
import random 

def random_item():
    random.randint()
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
Greg Isaacson
Greg Isaacson
Courses Plus Student 702 Points

I have done this...

am I on the right track..

``` import random def random_item(treehouse): Randomnumber = random.randint() return Randomnumber - 1 print(Randomnumber) ()

Greg Isaacson
Greg Isaacson
Courses Plus Student 702 Points

So I have adjusted it so it works like this:

import random
def random_item(treehouse):
    Randomnumber = random.randint(0, len(treehouse) - 1)
    return(Randomnumber) 
    print(???)
() 

2 Answers

Vedran Linić
PLUS
Vedran Linić
Courses Plus Student 18,802 Points
import random

def random_item(str):
    len_of_str = len(str) # you get lenght of string
    rand_los = random.randint(0, len_of_str) # you get number between 0 and lenght of string
    rand_los -=1 # you take 1 from that number
    return str[rand_los] # you get letter in the place of that string
Greg Isaacson
PLUS
Greg Isaacson
Courses Plus Student 702 Points

Ok I understand it now!:)

It was using [] that threw me off.

To explain my answer and understanding:

import random ------ This imports the random library.

Create my function:

Def random_item(treehouse): return treehouse[] <<<<< These [] brackets I understand now will return the "letter" based of the random integer.

So it goes like this:

return treehouse[random.randint(0,len(treehouse)-1)]