Python Python Basics (2015) Letter Game App Random Item

Andrei Oprescu
Andrei Oprescu
9,547 Points

can you tell me why my code is not doing the right thing?

I have a code:

import random

def random_item(astring): random_item = random.randint(0, len(astring)) return random_item

Can you please look at the question of the exercise and tell me what I did wrong?

Thanks

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

def random_item(astring):
     random_item = random.randint(0, len(astring)) 
        return random_item

2 Answers

First, your indentation doesn't match, return should be on the same level as the previous line. Also you're just returning a random number between 0 and the length of the string. You need to instead return the letter at that index. Try something like return astring[random.randint(0, len(astring) - 1)] I did -1 on the len of astring because the last number would otherwise be out of range, since we start counting from 0.

If you want to reuse your code you could do

def random_item(astring):
     random_number = random.randint(0, len(astring) - 1) 
     return astring[random_number]
Andrei Oprescu
Andrei Oprescu
9,547 Points

Thank you! I completely forgot that I had to tell the program to search the number in the argument.

Thanks