I've been asked to create a word guesser in python which outputs to the user how many letters are in the word, for example python has 6, so it would output 6. Then the user has 5 guesses to guess what letters are in the word, after these 5 guesses, the user is meant to guess the word. I've been able to display what letters have been guessed correctly by concatenating them to a new string, but I've not been able to display the correct position of the word and also if the letter appears twice in the word, essentially like hangman.
Question 1: How can I get the letters guessed correctly to appear in the order of the word and not the order they are guessed in?
Question 2: How do I get a repeating letter to show however many times it appears in the word?
Code below:
#WordGuesser
import random
WORDS = ("computer","science","python","pascal","welcome")
word = random.choice(WORDS)
correctLetters = ""
guesses = 0
print(
"""
Welcome to Word Guesser!
You have 5 chances to ask if a certain letter is in the word
After that, you must guess the word!
"""
)
print("The length of the word is", len(word))
while guesses != 5:
letter = input("Guess a letter: ")
if letter.lower() in word:
print("Well done", letter, "is in the word")
correctLetters += letter
print("Correctly guessed letters are: ",correctLetters)
guesses += 1
else:
print("No", letter, "is not in the word")
correctLetters += "-"
guesses += 1
guess = input("Please now guess a word that it could be!: ")
if guess == word:
print("Well done, you guessed it")
input("\n\nPress enter key to exit")
else:
("You did not guess it, the word was: ",word)
You should iterate over the word instead in order output the guessed letters in the word of the letters in the correct word. Use a set instead to keep track of the correct letters for efficient lookups since you only need it to determine whether or not a letter has been correctly guessed:
correctLetters = set()
while guesses != 5:
letter = input("Guess a letter: ").lower()
if letter in word:
print("Well done", letter, "is in the word")
correctLetters.add(letter)
print("Correctly guessed letters are: ", ''.join(letter if letter in correctLetters else '-' for letter in word))
else:
print("No", letter, "is not in the word")
guesses += 1
Demo: https://repl.it/@blhsing/WellmadeAlarmingInformation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With