Python Python Basics (2015) Letter Game App Random Item

CAN'T FIND THE WAY TO DO IT . PLEASE HELP

I don't know how the code will look like for this plz help me with your code

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

1 Answer

Hello Ashmit,

You are on the right track! Just remember:

  • The code you're writing (except the random import) goes inside of a function called random_item.
  • The len function takes a single iterable. You simply pass in the iterable passed into random_item.
  • Don't forget to subtract the length by one! Computers start counting at zero, so the last element is at the size of the list minus one.

With all of this in mind, you may write this:

PLEASE DO NOT COPY-AND-PASTE. Trust me, just read this code, and reproduce this code yourself. It's the best way to learn to code!

import random

def random_item(iterable):
    return iterable[random.randint(0, len(iterable) - 1)]

Happy coding! :zap: ~Alex