I am making a hangman game and I'm mostly finished. I'm trying to cover some common errors to prevent players from doing silly things like...
Numbers are invalid. I have added str.isalpha(): below my input, and it correctly displays the message to the user 'Only letters allowed'. But then it adds the number to the list of incorrect guesses and uses up a life.
Any suggestions on the best way to handle this and also the best way to add future errors into this game based on player input.
Here is a snippet of my code, a lot of code, apologies.
`
while True:
print("....................................")
player_guess = input("Want to live? Then guess a letter: ")
if player_guess.isalpha() is False:
print("Only letters are allowed!")
if player_guess in picked_word:
# This if statement sets index to 0
# and iterates through each letter within picked_word.
# Then calls the function to replace _ with player_guess
index = 0
for i in picked_word:
if i == player_guess:
correct[index] = player_guess
index += 1
replace_blank()
print(f"You guessed correct! {player_guess} is in the word")
else:
if player_guess not in incorrect:
# Checks if players guess is already guessed,
# if not, append to incorrect list.
incorrect.append(player_guess)
print(f"{player_guess} is not in the word, try again. \n")
print(f"Your incorrect guesses so far: {incorrect}")
replace_blank()
else:
print(f"You already guessed {player_guess}, try another letter.")
if len(incorrect) == 1:
print(
" _____ \n"
" | | \n"
" | \n"
" | \n"
" | \n"
" | \n"
" | \n"
"__|__\n"
)
`
I tried including the isalpha() method in the else statement of 'if player_guess not in incorrect' to pop the number off the list and display the error but that solution didn't do anything.
The issue here is the flow of your code. Think about your if else as branches of a tree.
Your current code:
Hopefully you can see that whether or not it isalpha, it will go through the next if else statement. Which is not what you want. So you should add a continue in the isalpha block which will skip everything and go to the next iteration of the loop.
Other comments:
player_guess.isalpha() is False
, you should be doingif not player_guess.isalpha()
(use the value itself instead of checking whether it IS false)if player_guess in ascii_letters
; don't forget to import itfrom string import ascci_letters
(orascii.lowercase
orascii_uppercase
)