Justin LeePro Student 593 Points
Help - Random item
Not sure what's wrong.
# 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
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' # 'T' 'Treehouse' # 'r' 'Treehouse' # 'e' 'Treehouse' # 'e' ... 'Treehouse' # '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]
hector alvarado15,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