dom daly dom daly - 10 days ago 2
Python Question

hangman only gets first letter of word

I have a python 3.5.2 hangman code:



def hangman():
wrongnums =[]
print("what is the word to be guessed?")
global guessnum
guessnum=input('>')
print("how many chances?")
global chances
chances=int(input('>'))
print("game in beginning")
global blanks
blanks = '_ ' * len(guessnum)
print()
print(blanks)
guessing()

def guessing():
global chances
print("guess a letter")
guess=input('>')
for letters in guessnum:
if guess == letters:
letterIndex = guessnum.index(guess)
global newBlanks
newBlanks = blanks[:letterIndex*2] + guess + blanks[letterIndex*2+1:]
print ("Guess is correct!")
check()

elif guess != letters:
chances -=1
print ("Guess is wrong! ", chances, " more failed attempts allowed.")
guessing()

def check():
print()
print("Word: ",newBlanks)
guessing()





When I go to guess the word, for example "car", "c" is fine and it says correct. But for "a" and "r" it says incorrect. Why is this? Here is the outcome:
Outcome

Answer

You are not checking the guessed letter vs the word, you are checking vs every single letter in the word due to the for loop so it checks vs the first, thinks its not wight and answers before it can check with the rest. Try this:

def hangman():
    wrongnums =[]
    print("what is the word to be guessed?")
    global guessnum
    guessnum=input('>')
    print("how many chances?")
    global chances
    chances=int(input('>'))
    print("game in beginning")
    global blanks
    blanks = '_ ' * len(guessnum)
    print()
    print(blanks)
    guessing()

def guessing():
    global chances
    print("guess a letter")
    guess=input('>')
    if guess in guessnum:
        letterIndex = guessnum.index(guess)
        global newBlanks
        newBlanks = blanks[:letterIndex*2] + guess + blanks[letterIndex*2+1:]
        print ("Guess is correct!")
        check()

    else:
        chances -=1
        print ("Guess is wrong! ", chances, " more failed attempts allowed.")
        guessing()

def check():    
    print() 
    print("Word: ",newBlanks)
    guessing()
Comments