Issue
I am aiming to not allow numbers to be registered when entered through input(). At current all chars are allowed (inc spaces and special chars). How do I prevent the below from registering and displaying numbers?
# Keep asking the player until all letters are guessed
while display != wordChosen:
guess = input(str("Please enter a guess for the {} ".format(len(display)) + "letter word: "))[0:1]
guess = guess.lower()
#Add the players guess to the list of used letters
used.extend(guess)
print("Attempts: ")
print(attempts)
# Search through the letters in answer
for i in range(len(wordChosen)):
if wordChosen[i] == guess:
display = display[0:i] + guess + display[i+1:]
print("Used letters: ")
print(used)
# Print the string with guessed letters (with spaces in between))
print(" ".join(display))
I tried using i for i in display if not i.isdigit()
within the print(" ".join(display))
as follows but that didnt solve the issue unless I'm implementing incorrectly:
# Print the string with guessed letters (with spaces in between))
print(" ".join(i for i in display if not i.isdigit()))
Current output on terminal example, I dont want numbers to be acknowledged or show up as a used guess:
Used letters: ['d', '4', '5', '6', '7', '8', '9']
Solution
Your choice in variable naming makes it a bit difficult to follow (it's unclear what display
should be)
But you seem to be on the right track, all you should need to do instead is after you get the input, before you extend the list, check if the input is valid and if so add it to the list, otherwise tell them it's invalid and continue
to ask for a new input:
guess = input(...)
if guess.isdigit():
# throw an error, or just tell the user the input is invalid.
continue
used.extend(guess.lower())
...
Answered By - Jab
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.