0

I am attempting a simple version of hangman. I'll add all of the frills such as a guess box later. Right now I can't get the core of the problem down.

I've tried looking at other's code but I wish to implement this without using enumerate. Is it possible? PS: I've also debugged it and verified that during the first loop, that secret_word_letter equals the user guess, yet doesn't update the string.

user_word = input("Enter a word you'd like to play with: ")
secret_word = user_word.lower()
hangman_word = len(user_word) * '_'
guesses = 0
game_Over = False
limit = int(len(user_word))

while not game_Over:
    if guesses == limit:
        print("You Lose! Game Over!")
        game_Over = True
    user_guess = input("Enter a letter you'd like to guess: ")
    for letter in secret_word:
        secret_word_letter = letter
        if secret_word_letter == user_guess:
            hangman_word.replace("_", user_guess)
            print(hangman_word)
            break
        else:
            print("You guessed wrong, try again!")
            guesses += 1
            break

Line 16 does not replace the blank hangman word string "_" with the user guess. Perhaps I am implementing the string.replace command wrongly.

Clappy
  • 1

1 Answers1

0

You must store the new value in the variable.

word = "glue"
word.replace("u", "_")
print(word) # glue

You can fix it by simply changing to variable = ...

word = "glue"
word = word.replace("u", "_")
print(word) # gl_e

So:

hangman_word = hangman_word.replace("_", user_guess)

Going forward, pay attention to what functions and methods return new values, and which modify values "in place." It's a useful thing to be mindful of when working with Python!

For example, appending to a list is "in place".

word = list(word) # ['g', 'l', '_', 'e']
word.append("!")
print(word) # ['g', 'l', '_', 'e', '!']
Charles Landau
  • 4,187
  • 1
  • 8
  • 24
  • While correct - this doesn't really explain why, in order to prevent future use of similar actions, which is because strings are immutable – OneCricketeer Jan 18 '19 at 05:39
  • I would argue that being aware of mutability isn't the same as being aware of what functions and methods make modifications in-place versus returning the modified value @cricket_007. I made an edit to that effect – Charles Landau Jan 18 '19 at 05:42