Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I parse a result and insert it into a variable?

I'm currently attempting to make a hangman game, whereby you can choose the number of letters in a word.

hLetters = int(input("How many letters? (4-16)\n"))

  def word(letters):
    if letters == 4:
      random.choice(list4)
    if letters == 5:
      random.choice(list5)
    # etc, etc

word(hLetters)

Obviously, this is inefficient - is there a method of getting the value of hLetters to be placed after "list", so that it automatically picks "list4" when the input is 4, or "list8" when the input is 8?

like image 382
Corsaka Avatar asked Nov 22 '25 14:11

Corsaka


2 Answers

You could place all you lists in a dictionary -

words_lists = {4 : list4, 5: list5}

And choose randomly from this dict values -

random.choice(words_lists[letters])
like image 64
Tom Ron Avatar answered Nov 24 '25 03:11

Tom Ron


You could use a list of list for this

letter = 4 
listoflist=[list4,list5,list6,..list16]
print(random.choice(listoflist[letter-4]))
like image 39
Albin Paul Avatar answered Nov 24 '25 04:11

Albin Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!