-3

It's word library from words import words

I chose a random word and I stuck here word_list= [letter if letter in used_letters else '-' for letter in word] I did not understand that.

import random 
from words import words
LIVES=7

def valid_word(words):
    word=random.choice(words)
    while ' ' in word or '_' in word:
        words=random.choice(words)
    return word.upper()

def hangman():
    word=valid_word(words)
    word_letters = set(word)
    used_letters = set()
    
    while len(word_letters) > 0 and LIVES > 0:
        print(f"You have {LIVES} lives left and you have these letters",' '.join(used_letters))

        word_list= [letter if letter in used_letters else '-' for letter in word]
        print(word_list)

        

hangman()
halfer
  • 19,824
  • 17
  • 99
  • 186
codeRunner
  • 13
  • 5
  • 2
    What *do* you understand about it? – Scott Hunter Aug 03 '22 at 18:46
  • Does this answer your question? [What does "list comprehension" and similar mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-and-similar-mean-how-does-it-work-and-how-can-i) – TheFungusAmongUs Aug 03 '22 at 18:56

3 Answers3

0
word_list=[letter if letter in used_letters else '-' for letter in word]

is exactly the same as:

word_list = []
for letter in word:
   if letter in used_letters:
      word_list.append(letter)
   else 
      word_list.append('-')

Same logic, different syntax.

JNevill
  • 46,980
  • 4
  • 38
  • 63
0

read it backwards, to a degree:

word_list= []

for letter in word:
    if letter in used_letters:
        word_list.append[letter]
    else:
        word_list.append['-']

I think that coveres it. When it comes to list comprehensions, i dont know how to explain them really, i know it took me a lot of practice to be comfortable with them and to use them. good luck pal

Gregory Sky
  • 140
  • 9
0

When I'm reading them, I find it helpful to insert a newline similar to the following:

word_list = [letter 
             if letter in used_letters else '-' 
             for letter in word]
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93