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 trialJohn Cuddihy
5,493 Pointsreturning random integer as member in a string
Could someone look at this and give me pointers at what I need to be doing, getting very frustrated as this is the 5th exercise in a row I'm not able to complete, getting no where
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item([Treehouse]):
num = random.randit([Treehouse])-1
while num > 0 and num <= len([Treehouse]):
return num in [Treehouse]
2 Answers
Steve Hunter
57,712 PointsHi John,
I got through this without a while loop. I took the incoming string (the parameter) and then used its length and zero with randint
to assign a random number, between length and zero, into num
, as you did. I then returned the [num]
element of the input_string
, like so:
import random
def random_item(input_string):
num = random.randint(0, len(input_string) - 1)
return input_string[num]
I hope that helps,
Steve.
Jeremy Hill
29,567 PointsTry it like this:
import random
def random_item(some_string):
index = random.randint(0, len(some_string)-1)
return some_string[index]
John Cuddihy
5,493 PointsJohn Cuddihy
5,493 PointsThanks Steve
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsNo problem!