First of all, please pardon my English. It's my second language.
I'm trying to complete writing a hangman game.
Here's my rough code:
WORDS_LIST = ["I do not know"]
answer = list(random.choice(WORDS_LIST))
for char in answer:
if (char.isalpha()):
list1.append(char)
else:
list1.append("")
for char in list1:
if char == "":
guess_box.append(" ")
else:
guess_box.append("_")
print(' '.join(guess))
player_choice = input("\nguess a letter: ")
for item in range(0, len(ANSWER)):
if ANSWER[item] == player_choice:
guess_box[item] = player_choice
elif ANSWER[item][0] == player_choice[0]:
guess_box[item] = player_choice.upper()
As you can see this print out the pattern
_ _ _ _ _ _ _ _ _ _
I have a problem with the first capital letter. I'm not sure how should I compare user input with a single capital letter in a list. Please help me figure this out, anyone?
Example Output:
I do not know
As the comments send you can use char.lower()
but I saw some other things that could help you so here are some more tips and tidbits.
First you can create your lists using list comprehension as it is shorter and fairly easy to read.
import random
WORDS_LIST = ["I do not know"]
# A list of characters
answer = list(random.choice(WORDS_LIST))
# A set of all the letters (converted to lowercase) that are contained
# in the answer. sets are significantly faster to search through.
letters = {char.lower() for char in answer if char.isalpha()}
guessed_letters = set()
# Note the syntax used above and here. This is called list
# comprehension.
# This is the same as:
# guess_box = []
# for char in answer:
# if char.isalpha():
# guess_box.append("_")
# else:
# guess_box.append(char) # Just use the space.
guess_box = ["_" if char.isalpha() else char for char in answer]
Then you can handle your input logic:
print(' '.join(guess_box))
player_choice = input("\nguess a letter: ")
while player_choice:
print(f"You chose: {player_choice}")
# Convert user input to lower case
player_choice = player_choice.lower()
# If this letter was guessed before:
if player_choice in guessed_letters:
print("You guessed this letter already.")
else:
guessed_letters.add(player_choice)
# Check if this choice is in our word
if player_choice in letters:
# If we have this letter then change
# the guess_box
for index, val in enumerate(answer):
# Of the user input
if val.lower() == player_choice:
guess_box[index] = val
else: # The letter is wrong
print("That letter didn't fit")
print(' '.join(guess_box))
player_choice = input("\nguess a letter: ")
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments