我正在尝试用Python进行猜词游戏,但是最后一部分让我有些困惑。
这是我直到现在的代码:
word_tuple = ("c", "o", "d", "e", "c")
word = ""
word = input("Give a word of " + str(len(word_tuple)) + " characters: ")
while len(word) != len(word_tuple):
if len(word) != len(word_tuple):
print("Wrong!")
word = input("Give a word of " + str(len(word_tuple)) + " characters: ")
for i in range(len(word_tuple)):
print(word_tuple[i], end="")
基本上,循环检查是否插入5个字符的单词,如果插入,则将单词与元组的字符进行比较。如果1个或多个字符正确,它将打印正确的字符,而没有被猜到的字符将被一个符号遮住,例如'*'。
令人困惑的部分是我必须检查输入的单词是否具有与元组匹配的字符,然后打印出正确的字符。
例如:
Give a word of 5 characters: Python
Wrong!
Give a word of 5 characters: Candy
Almost there! The word is "C*d*c"
Give a word of 5 characters: Denim
Almost there! The word is "C*dec"
Give a word of 5 characters: Codec
You found the word!
任何帮助将不胜感激。
答案 0 :(得分:2)
您的问题是您的单词打印不正确,并且打印的时间不在此范围内,这是您可以尝试的答案
word_tuple = ("c", "o", "d", "e", "c")
# We use this list to keep in memory the letters found
found = [False] * len(word_tuple)
word = ""
# The `all` method return True only if the list contains only True values
# Which means, while all letters are not found
while not all(found):
# the `lower` method allows you to not take in account the uppercases
word = input("Give a word of " + str(len(word_tuple)) + " characters: ").lower()
if len(word) == len(word_tuple):
for charac in word_tuple:
if charac in word:
found = [b or word_tuple[index] in word for index, b in enumerate(found)]
# The `any` method return True only if the list contains at least one True value
# Which means we print Wrong only if there is no letter found
if not any(found):
print('Wrong!')
else:
print('Almost there! The word is "', end='')
for i in range(len(word_tuple)):
if found[i]:
print(word_tuple[i], end="")
else:
print('*', end='')
print('"')
else:
print('Wrong!')
# The method `join` allows you to join every string of an iterable
# Which means it joins every character of your tuple to a printable string
while word != ''.join(word_tuple):
print('Close, try again')
word = input("Give a word of " + str(len(word_tuple)) + " characters: ").lower()
print('You found the word!')
一个练习可以是用不同的方法重构此代码