Python Python Basics (2015) Letter Game App Random Item

Justin Lee
PRO
Justin Lee
Pro Student 593 Points

Help - Random item

Not sure what's wrong.

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

import random

def random_item(treehouse):
    answer = random.randint(0, len(treehouse) -1):
        return answer

3 Answers

When we define the function random_item we are expecting a string to be used as an argument. Remember characters in strings can be accessed by their index beginning at 0. For example, in the string 'Treehouse' the 0th index is 'T' while the last character 'e', is the 8th index . Then we define the variable random_index it chooses a random integer between 0-8 (len(string)-1). Finally, we return the character at the random_index with string[random_index].

I hope this is clear as I am still learning myself.

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

'Treehouse'[0] # 'T'

'Treehouse'[1] # 'r'

'Treehouse'[2] # 'e'

'Treehouse'[3] # 'e'
...
'Treehouse'[8] # 'e'

In your code you are only returning a random index within the length of the paramater(treehouse).

def random_item(string):
    random_index = random.randint(0, len(string) - 1)
    return string[random_index]
Justin Lee
Justin Lee
Pro Student 593 Points

I don't quite get it. Can you please explain?

hector alvarado
hector alvarado
15,781 Points

I think the problem is the ":" on the statment, and the indentation of the return statement, remember keep the same indentation per block.

def random_item(treehouse):
    answer = random.randint(0, len(treehouse) -1)
    return answer