Skip to content
Advertisement

Hangman in Python: Type error raised when trying to display guessed letters along blank space

the following codes are for the Hangman game. It gets a type error for the assignment display = list("_" * len(chosen_word)), saying that it is a Nonetype. Is this because chosen_word is not assigned (which is another error in itself)?. How can it be corrected? Any other suggestion to improve the code is also welcomed.

import random

Dictionary = {"fruits": "watermelon", "buildings": "apartment", "mammal": "horse", "occupation": "fireman"}


def choose_word():
    hint, chosen_word = random.choice(list(Dictionary.items()))
    print("Hint: " + hint)
    blank = []
    for letter in chosen_word:
        blank.append("_")
    print("".join(blank))
    return chosen_word


def draw_hangman(attempt):
    stages = [  # final state: head, torso, both arms, and both legs
                """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |     / \
                   -
                """,
                # head, torso, both arms, and one leg
                """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |     / 
                   -
                """,
                # head, torso, and both arms
                """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |      
                   -
                """,
                # head, torso, and one arm
                """
                   --------
                   |      |
                   |      O
                   |     \|
                   |      |
                   |     
                   -
                """,
                # head and torso
                """
                   --------
                   |      |
                   |      O
                   |      |
                   |      |
                   |     
                   -
                """,
                # head
                """
                   --------
                   |      |
                   |      O
                   |    
                   |      
                   |     
                   -
                """,
                # initial empty state
                """
                   --------
                   |      |
                   |      
                   |    
                   |      
                   |     
                   -
                """
    ]
    return stages[attempt]


def play_hangman(chosen_word):
    attempt = 6
    guessed = False
    guessed_letters = []
    display = list("_" * len(chosen_word))
    while attempt > 0 and not guessed:
        print(draw_hangman(attempt))
        player_guess = input("nPlease guess a letter between A-Zn")
        letter = 0
        if len(player_guess) == 1 and player_guess.isalpha() and player_guess in chosen_word:
            while chosen_word.find(player_guess, letter) != -1:
                letter = chosen_word.find(player_guess, letter)
                display[letter] = player_guess
                letter += 1
                guessed_letters.append(player_guess)
            print("".join(display))
            if display[letter] == chosen_word:
                guessed = True
                print("Congratulation, you won!")
        elif player_guess in guessed_letters:
            print("You have already guessed this letter")
        else:
            print("Your guess is not valid")
            attempt -= 1
        print(draw_hangman(attempt))
    else:
        print("You ran out of attempts")


play_hangman(choose_word())

Error 1 (resolved):

Traceback (most recent call last):
  File "/Users/owly/PycharmProjects/pythonProject1/main12.py", line 119, in <module>
    play_hangman(choose_word())
  File "/Users/owly/PycharmProjects/pythonProject1/main12.py", line 94, in play_hangman
    display = list("_" * len(chosen_word))
TypeError: object of type 'NoneType' has no len()

Error 2 : after a few guesses, index gets of range

Traceback (most recent call last):
  File "/Users/owly/PycharmProjects/pythonProject1/main12.py", line 120, in <module>
    play_hangman(choose_word())
  File "/Users/owly/PycharmProjects/pythonProject1/main12.py", line 107, in play_hangman
    if display[letter] == chosen_word:
IndexError: list index out of range
w__er_e__n

Process finished with exit code 1

Advertisement

Answer

Following code worked perfectly,

str1 = ''.join(display)
if str1 == chosen_word:
       guessed = True
       print("Congratulation, you won!")
       attempt=-1

I have just added above code and some minor changes in if-else conditions and some print statements. Remove extra print statements if you want!

Full code-

import random
Dictionary = {"fruits": "watermelon", "buildings": "apartment", "mammal": "horse", "occupation": "fireman"}


def choose_word():
    hint, chosen_word = random.choice(list(Dictionary.items()))
    print("Hint: " + hint)
    blank = []
    for letter in chosen_word:
        blank.append("_")
    print("".join(blank))
    return chosen_word


def draw_hangman(attempt):
    stages = [  # final state: head, torso, both arms, and both legs
                """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |     / \
                   -
                """,
                # head, torso, both arms, and one leg
                """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |     / 
                   -
                """,
                # head, torso, and both arms
                """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |      
                   -
                """,
                # head, torso, and one arm
                """
                   --------
                   |      |
                   |      O
                   |     \|
                   |      |
                   |     
                   -
                """,
                # head and torso
                """
                   --------
                   |      |
                   |      O
                   |      |
                   |      |
                   |     
                   -
                """,
                # head
                """
                   --------
                   |      |
                   |      O
                   |    
                   |      
                   |     
                   -
                """,
                # initial empty state
                """
                   --------
                   |      |
                   |      
                   |    
                   |      
                   |     
                   -
                """
    ]
    return stages[attempt]


def play_hangman(chosen_word):
    attempt = 6
    guessed = False
    guessed_letters = []
    display = list("_" * len(chosen_word))
    
    while attempt > 0:
        if not guessed:
            print(draw_hangman(attempt))
            player_guess = input("nPlease guess a letter between A-Zn")
            letter = 0
            if len(player_guess) == 1 and player_guess.isalpha() and player_guess in chosen_word and player_guess not in guessed_letters:
                while chosen_word.find(player_guess, letter) != -1:
                    print("running while:"+str(letter))
                    letter = chosen_word.find(player_guess, letter)
                    display[letter] = player_guess
                    letter += 1
                    guessed_letters.append(player_guess)
           
                print("".join(display))
                print(display)
                str1 = ''.join(display)
                if str1 == chosen_word:
                    guessed = True
                    print("Congratulation, you won!")
                    attempt=-1
            elif player_guess in guessed_letters:
                print("You have already guessed this letter")
            else:
                print("Your guess is not valid")
                attempt -= 1
            print(draw_hangman(attempt))
    else:
        print("You ran out of attempts")


play_hangman(choose_word())

let me know if there is any difficulty!!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement