'For loop printing all steps, but i only need the last
Im making a hangman game in python. and now i got stuck in a problem. i want the for loop to print display that says
wanted output: ['_', '_', '_', '_', '_']
but it prints:
['_']
['_', '_']
['_', '_', '_']
['_', '_', '_', '_']
['_', '_', '_', '_', '_']
I understand this is the for loop, but how do I make it only print what I want? thank you for your time and help!
import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
# Testing code
print(f'Pssst, the solution is {chosen_word}.')
display = []
for letter in chosen_word:
display.append("_")
print(display)
guess = input("Guess a letter: ").lower()
Solution 1:[1]
I implement this to practice. Sure that can be more elaborate but for a reference should work:
import random
WORD_LIST = ["aardvark", "baboon", "camel"]
MAX_POINTS = 5
chosen_word = random.choice(WORD_LIST)
word = ["".join("_") for i in chosen_word]
print(word)
def guessing():
# Initial setup
initial_points = MAX_POINTS
print(f"initial_points: {initial_points}")
# store the guess history
history = set()
while True:
if "_" not in word:
print('you WIN!!')
break
elif initial_points < 1:
print('you LOSE!!')
break
guess = input("Guess a letter: ").lower()
# decrement initial points
if guess not in chosen_word \
and guess not in history \
and guess not in word:
initial_points -= 1
for i, c in enumerate(chosen_word):
if guess == c:
word[i] = guess
# Not decrement twice
history.add(guess)
# display
print(f"Points: {initial_points} - {word}")
print(f"Guessed letters: {history}")
guessing()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Franz Kurt |
