hangman python printing issue as beginner - Stack Overflow

admin2025-04-17  3

The problematic section has been separated and rewritten from the main code. It should be printing the correctly guessed letters along with the ones not yet guessed as _. However, the result is that the correct guesses will be printed out with excessive underscores.

As following:

camel
_____
Guess a letter: c
c____
Guess a letter: a
c_____a___

The problematic code:

import random as r
word_list = ["aardvark", "baboon", "camel"]
chosen_word = r.choice(word_list)
print(chosen_word)
placeholder = ""
length = len(chosen_word)
for position in range(length):
    placeholder += "_"
print(placeholder)
display = ""
while 1 > 0:
    guess = input("Guess a letter: ").lower()
    for letter in chosen_word:
        if letter == guess:
            display += letter
        else:
            display += "_"
    print(display)

The problematic section has been separated and rewritten from the main code. It should be printing the correctly guessed letters along with the ones not yet guessed as _. However, the result is that the correct guesses will be printed out with excessive underscores.

As following:

camel
_____
Guess a letter: c
c____
Guess a letter: a
c_____a___

The problematic code:

import random as r
word_list = ["aardvark", "baboon", "camel"]
chosen_word = r.choice(word_list)
print(chosen_word)
placeholder = ""
length = len(chosen_word)
for position in range(length):
    placeholder += "_"
print(placeholder)
display = ""
while 1 > 0:
    guess = input("Guess a letter: ").lower()
    for letter in chosen_word:
        if letter == guess:
            display += letter
        else:
            display += "_"
    print(display)
Share Improve this question edited Jan 30 at 17:03 khelwood 59.3k14 gold badges89 silver badges115 bronze badges asked Jan 30 at 16:32 Chris Zimmer N0chi11ZChris Zimmer N0chi11Z 11 bronze badge 1
  • You make display longer every time there is a guess. – khelwood Commented Jan 30 at 17:04
Add a comment  | 

4 Answers 4

Reset to default 2

First of all, convert the chosen word into a list (this will make it easier to find the index). Second, you are adding the letter with the underscores each time the user guesses; instead, you have to replace the underscore with the letter. Here is an implementation:

from random import choice

word_list = ["aardvark", "baboon", "camel"]

chosen_word_list = list(choice(word_list))
print(''.join(chosen_word_list))

man_dies_in = 6

display = ['_' for _ in range(len(chosen_word))]

while man_dies_in > 0:
    guess = input('Guess a letter: ').lower()
    if guess in display:
        print('You already guessed that letter.')
        continue
    if guess in chosen_word_list:
        for i, letter in enumerate(chosen_word_list):
            if letter == guess:
                display[i] = guess
        print(''.join(display))
    else:
        print('That letter doesn\'t appear in the word.')
        man_dies_in -= 1
    print(f'You have {man_dies_in} lives left.')

    if '_' not in display:
        break

print('You died.' if '_' in display else 'You won!')

Here I also added a game over mechanism, which checks when the user has made the maximum amount of guesses allowed.

You are adding characters to the display field every time there is a guess, so it creates too many characters. You need to start with an empty string each time. You also need to keep a copy of each guess so that after every guess you can build up the word from all the previous guesses, remembering to terminate the loop when all letters have been found. So you need something like this at the end:

letters = ""
while 1 > 0:
    display = ""
    blanks = False
    guess = input("Guess a letter: ").lower()
    if guess in letters:
        print(F"You already chose {guess}, please try again")
    else:
        if guess in chosen_word:
            letters += guess   # add to list of valid letters
        for letter in chosen_word:
            if letter in letters:
                display += letter
            else:
                display += "_"
                blanks = True
        print(display)
        if not blanks:
            break 

After hours of single digit braincell activities, i found the issue, display wasn't in the while loop, and combining the answers given. It worked.

import random as r
word_list = ["aardvark", "baboon", "camel"]

chosen_word = r.choice(word_list)
print(chosen_word)
placeholder = ""
length = len(chosen_word)
for position in range(len(chosen_word)):
    placeholder += "_"
print(placeholder)

game_over = False
correct = []
while not game_over:
   guess = input("Guess a letter: ").lower()
   display = ""
   for letter in chosen_word:
        if guess in letter:
           display += letter
           correct.append(guess)
       elif letter in correct:
            display += letter
       else:
           display += "_"
   print(display)
if "_" not in display:
    game_over = True

It's not final yet.

It should be printing the correctly guessed letters along with the ones not yet guessed as _. However, the result is that the correct guesses will be printed out with excessive underscores.

As you can see, since it is boolean (true and false), you cannot use 1 > 0.

I include the variables game_over and correct_letters in my declaration.

Inside the while/else condition block, move display = ""

If the game is over, I'll include.

You are ready to go.

Script (only two small changes: correct_letters and game_over)

import random

    

word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
print(chosen_word)

placeholder = ""

word_length = len(chosen_word)

for position in range(word_length):
    placeholder += "_"
print(placeholder)


game_over = False
correct_letters = []


while not game_over:
    guess = input("Guess a letter: ").lower()
    display = ""

    if guess not in chosen_word:
        continue

    for letter in chosen_word:
        if letter == guess:
            display += letter
            correct_letters.append(guess)
        elif letter in correct_letters:
            display += letter
        else:
            display += "_"


    print(f'display : {display}')
    

    if "_" not in display:
        print("You win.")        
        game_over = True
  

Output:

aardvark
________
Guess a letter: v
display : ____v___
Guess a letter: r
display : __r_v_r_
Guess a letter: a
display : aar_var_
Guess a letter: d
display : aardvar_
Guess a letter: k
display : aardvark
You win.

转载请注明原文地址:http://anycun.com/QandA/1744905221a89280.html