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

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