timelyfor
timelyfor

Reputation: 49

how do I subtract 1 from this? (Python)

I'm coding a simple hangman game, but when I subtract 1 from lives, 1 is subtracted no matter the condition. How would I code this in a way that 1 is subtracted only if guess is not equal to any letter in the word?

lives = 6   < ---- starting num of lives
game_over = False


while not game_over:
  guess = input("Guess a letter. ") 
  for pos in range(len(chosen_word)): < - - chosen word is the randomly chosen word
    letter = chosen_word[pos] 
    if letter == guess:
      display[pos] = letter
  print(display)
  if display.count("_") == 0:
    print("Game over. ")
    game_over = True
  elif letter != guess:         < these lines are meant to subtract a life only if 
    lives = lives - 1           < letter is not equal to guess, but they actually
    print(f"Lives: {lives}")    < subtract no matter what. How do I fix this? 
  elif lives == 0:              
    game_over = True
    print("Game over. ")

Upvotes: 1

Views: 767

Answers (1)

Samwise
Samwise

Reputation: 71477

letter still has whatever value it had at the end of this loop:

  for pos in range(len(chosen_word)): < - - chosen word is the randomly chosen word
    letter = chosen_word[pos] 

i.e. it will always be the last letter in the word after the loop has finished. What you want to test for instead is whether any letter in chosen_word is the same as guess, which is the same as testing whether guess is in chosen_word:

  elif guess not in chosen_word:
    lives -= 1
    print(f"Lives: {lives}") 

Note that in that earlier loop, you can get letter automatically with enumerate, and then you also don't need to do the range(len()) thing:

  for pos, letter in enumerate(chosen_word):
    if letter == guess:
      display[pos] = letter

Upvotes: 1

Related Questions