我如何停止函数以迭代列表中的所有项目
我正在python写一个简单的单词猜测游戏。我没有使用列表,而是在.txt
文件中使用的所有单词称为函数的参数。列表本身很好。
游戏要求用户输入字母。输入字母后,如果它匹配由随机函数随机选择的单词之一,则可以相应地给出点。
问题在于,当功能运行时,用户输入的字母会通过列表中的所有单词迭代。如何解决此问题?
def guess_game(data):
word = random.choice(data)
print("alright, guess the first letter:")
ans = input("Enter a letter to guess: ")
print(ans)
counter = 0
tries = 15 #how many tries a user is allowed to make
for match in word:
if ans in match:
counter += 10
tries -= 1
print("That's right, 10 points added")
print(f"You have {tries} tries left. ")
elif ans not in match:
counter -= 10
tries -= 1
print("That's wrong, 10 points deducted")
print(f"You have {tries} tries left. ")
I am writing a simple word guessing game in python. Instead of using a list, I have all the words for the game in a .txt
file called as the parameter of a function. The list itself is fine.
The game requires the user to enter a letter. Once the letter is entered, if it matched one of the words that is randomly selected by the random function, it gives points accordingly.
The problem is that when the function runs, the entered letter by the user iterates through all the words in the list. How do I fix this issue?
def guess_game(data):
word = random.choice(data)
print("alright, guess the first letter:")
ans = input("Enter a letter to guess: ")
print(ans)
counter = 0
tries = 15 #how many tries a user is allowed to make
for match in word:
if ans in match:
counter += 10
tries -= 1
print("That's right, 10 points added")
print(f"You have {tries} tries left. ")
elif ans not in match:
counter -= 10
tries -= 1
print("That's wrong, 10 points deducted")
print(f"You have {tries} tries left. ")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很少的想法:
这是我的建议:
您也可以列出列表已经猜到的字母,因此您可以在找到所有需要的字母后立即给予反馈。
few ideas:
Here is my suggestion:
You could also make a list of letter that were already guessed so you can give the player feedback as soon as they found all the needed letters.
“ in”关键字本身仅检查集合中变量的第一次出现。
但是,如果您想更具体,请将输入的单词分配给变量,然后在IF语句中匹配列表时使用break关键字。
The 'in' keyword itself checks only the first occurrence of a variable in a collection.
However if you want to be more specific, assign your entered word to a variable and then use break keyword after it matches under the if statement while iterating through the list.