I'm relatively new to sub strings on python and have encountered a problem with it in my hangman game. The problem is pretty random like when you guess the second letter in the word say 'e' (in hello) it does not register as in it doesn't change the blanks. And with the third letter say 'l' it places in the second blank position say h l _ _ _ instead of h _ l _ _. Here is my code:
previousguesses = ''
secret = "hello"
blanks = "_ "*len(secret)
detectletter= list(secret)
bruh = list(detectletter.pop())
game = 0
while game == 0:
print(blanks)
guess = input("\n" "l for a letter guess, w for a word guess")
if guess == "l":
letterguess = input("What is your letter guess")
if letterguess in previousguesses:
print("You have already guessed that. Here are the letters you have guessed:" + previousguesses)
if letterguess in detectletter:
if letterguess not in previousguesses:
print("Correct!")
guessbruh = str(previousguesses + ' ' + letterguess)
guessbruh.replace('"', '')
for checker in range(10):
locblanks = secret.find(letterguess)
locblanks = locblanks + 1
blanks = blanks[:locblanks].replace('_', letterguess) + blanks[locblanks:]
if blanks == secret:
print("Correct! You Win!")
game = 1
print("You have guessed these letters :" + previousguesses)
if letterguess not in detectletter:
print("Wrong")
guessbruh = str(previousguesses + ' ' + letterguess)
guessbruh.replace('"', '')
print("You have guessed these letters :" + previousguesses)
elif guess == "w":
wordguess = input("What is your word guess")
if wordguess == secret:
print("Correct! You Win!")
game = 1
Try breaking down your problem in to smaller more manageable parts. For example this below example shows how to output the word showing only the currently guessed letters.
secret = "hello"
guesses = ['e','o']
def getWordWithGuesses(word, guesses):
"""If the word is hello and we have guessed 'o' and 'e', return '_e__o'"""
guess_word = ""
for letter in word:
if letter in guesses:
guess_word += letter
else:
guess_word += "_"
return guess_word
print(getWordWithGuesses(secret,guesses))
Consider a small function for each part of your program. You can get each part working individually and then join them together later.
The problem with your code is around the for checker in range(10)
section. I'm not sure what you are trying to do there, but you aren't using checker
so you won't be indexing over each character in the word. Note how I use for letter in word
, this will work for a word of any length not just those of length 10.