Reputation: 19
I would like to find out where in 'words' the users 'guess' is, and then print the guessed character alongside '_' in the correct position:
words = "apple"
print("_ " *len(words), end="")
guessed = ""
for char in words:
guess = input("\n start guessing")
if guess in words:
for i in guess:
guessed += guess
else:
print("wrong letter")
Upvotes: 1
Views: 53
Reputation: 1226
The following should work:
word = "apple"
guessed = "_ " *len(word)
print(guessed)
while '_' in guessed:
guess = input("\nGuess a letter\n")
if len(guess) == 1:
if guess in word:
guessed = ' '.join([x if x == guess or x in guessed else '_' for x in word])
print(f"You guessed correct, the letter {guess} is in the word:\n{guessed}")
else:
print(f"Sorry, {guess} ist not correct.")
print('Congratulations, you solved it!')
I replaced the for
with a while
loop that exits, when there are no underscores left in the word the user has to guess. This allows the user to guess until the word is complete. If you want to limit the user to certain amount of guesses, you could add a counter variable and break
the loop accordingly.
The script furthermore checks if the input is a single character with if len(guess) == 1:
. The list comprehension then replaces underscores based on the condition that whether the user already guessed the character earlier on (x in guessed
) or in this round (x == guess
).
Note that this solution involving f-strings works in python versions >3.6. If you're using another python version, you'll have to replace the f-strings. In addition, I should mention that this code is case sensitive. So if your word
starts with an uppercase letter and the user guessed the first letter but as a lowercase, the script will consider it as a wrong letter.
Upvotes: 2