【问题标题】:How to make a hangman remember your guesses in Python?如何让刽子手记住你在 Python 中的猜测?
【发布时间】:2021-03-16 09:39:05
【问题描述】:

这是我目前写的: 那是一个刽子手游戏。猜完字母后,代码应该记住之前的猜测。但事实并非如此。

我应该对此代码进行哪些更改?

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
 
print(f'Pssst, the solution is {chosen_word}.')
 
display = []
for i in range(0, len(chosen_word)):
    display.append("_")
    listToStr = ' '.join(display) 
print(listToStr)
 
end = False
 
while not end:
  guess = input("Guess a letter: ").lower()
 
  result = []
  for letter in chosen_word:
      
    if letter == guess:
      result.append(guess)
    else:
      result.append(display[i])
 
  result = ' '.join(result) 
 
  print(result)
  if "_" not in display:
    end = True

【问题讨论】:

  • 这是因为您没有更改display。在猜测之后,您应该将display 更新为result 的值,因为result 现在包含当前的猜测。

标签: python for-loop while-loop


【解决方案1】:

在您的 while 循环中,每次迭代都会初始化结果数组。 这意味着每次循环都会清除结果,并且仅将最后一次猜测添加到新的空结果数组中。

【讨论】:

  • 太棒了。解决了这个问题。但是... ``` Pssst,解决方案是土豚。 _ _ _ _ _ _ _ _ 猜一个字母:a a a _ _ _ a _ _ 猜一个字母:d a a _ _ _ a _ _ _ _ _ d _ _ _ _ ```那么这种输出就来了。跨度>
猜你喜欢
  • 2021-07-31
  • 1970-01-01
  • 2015-11-20
  • 2012-10-15
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
相关资源
最近更新 更多