Reputation: 33
I'm trying to code a hangman game using python and I'm having issues getting the correct length of a string to return when I run the code. It will return things like ['clouds'] 10
or ['mango'] 9
or ['rose'] 8
when it should actually be returning ['clouds'] 6
and ['mango'] 5
and ['rose'] 4
.
Please help me see what I'm doing wrong!
Here's what I wrote:
import random
word_list = ['tiger','dog','cake','disney','donut','rose','clouds','movies','sparkle','yoga','walrus','candle','mango','taco','flowers']
word = str(random.sample(word_list, 1))
word_len = len(word)
print(word, word_len)
Upvotes: 0
Views: 103
Reputation: 1300
You're using wrong method
import random
word_list = ['tiger','dog','cake','disney','donut','rose','clouds','movies','sparkle','yoga','walrus','candle','mango','taco','flowers']
# return a k length list of unique elements chosen from the population sequence or set
# where k is 1, population sequence is word_list
print(random.sample(word_list, 1))
# to get random item from list you have to use random.choice
print(random.choice(word_list))
Upvotes: 2
Reputation: 13401
random.sample(word_list, 1)
returns single item list
like ["sparkle"] and you're converting it into str
so it adds [""]
around the word so word becomes '["sparkle"]'
I think you need:
import random
word_list = ['tiger','dog','cake','disney','donut','rose','clouds','movies','sparkle','yoga','walrus','candle','mango','taco','flowers']
word = random.sample(word_list, 1)
word_len = len(word[0])
print(word, word_len)
Output:
['sparkle'] 7
Upvotes: 2