Python Python Basics (2015) Letter Game App Random Item

I've gotten the right answer on another text-editor. I'm not sure why I was fault here.

I'm not sure whether I've understood the question correctly.

From my understanding, we're required to

Generate a random number based on the length of our iterable

Based on the generated number, be able to output the string alphabet of the "index"
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"

import random

def random_item(input):
    random_num = random.randint(0,8)
    input = "Treehouse" 
    random_string = input[random_num]


2 Answers

Boban Talevski
Boban Talevski
24,775 Points

There are several issues with the code you have.

You should not assign a value to the input variable, it's something that will be sent in to the function and your code needs to handle it in general terms. That is, get a random number between 0 and the length of input(whatever its value is, you shouldn't care), and use that random number as an index to return an item from the input variable.

The important part is to return the item, not print it, which is the other issue with your code.

Here is a simple one line solution

def random_item(input):
    return input[random.randint(0, len(input))]

Thank you. You've definitely pointed me in the right direction.

Ever grateful m8!

Boban Talevski
Boban Talevski
24,775 Points

Glad to help. You could mark my answer as best answer so the problem can be treated as solved. ;)