我是一名初学者,连续几周,这是我学习一些基础知识后的第一个程序。这是一个刽子手游戏,但它是一个非常粗糙的版本,没有视觉效果(稍后会出现)。当我运行它时,它允许我选择一个字母,但之后它给了我错误“noneType对象不可迭代”
任何人都能解释为什么会这样吗? 很抱歉代码质量非常低,但当我浏览其他类似错误的问题时,代码太复杂了,我无法应用于我的情况
import time
import random
"""This is a hang man game
"""
name = input("what is your name?")
print("Hello" + " " + name)
time.sleep(1)
print("Ok, lets paly hangman, let me choose a word......")
time.sleep(1)
print("Thinking, thinking, thinking....")
time.sleep(3)
print("AHA! got it, ok " + name + ", take your first guess")
time.sleep(1)
def hangman_game():
word_list = ["herd", "heaven", "manly", "startle"]
number = random.randint(0, len(word_list) - 1)
secret_word = word_list[number] #chooses a word from the word list
blank_char = "-"
word_length = len(secret_word) * blank_char
word_length_split = list(word_length)
print("Try and guess the word: ", word_length) #displays the length of the word in '_'
previous_guesses = []
guesses_taken = 0
turns = 10
secret_word_list = list(secret_word)
while turns > 0:
letter_guessed = input("Pick a letter: ")
if letter_guessed in previous_guesses:
print("You have already guessed this letter")
else:
previous_guesses = previous_guesses.append(letter_guessed)
if letter_guessed in secret_word_list:
secret_word_list = secret_word_list.remove(letter_guessed)
guesses_taken = guesses_taken + 1
print("That is correct," + letter_guessed + " is in the word")
time.sleep(1)
else:
turns = turns - 1
guesses_taken = guesses_taken + 1
print("Try again")
print("Sorry mate, no turns left, play again?")
hangman_game()
答案 0 :(得分:4)
更改previous_guesses = previous_guesses.append(letter_guessed)
到previous_guesses.append(letter_guessed)
另外secret_word_list = secret_word_list.remove(letter_guessed)
到secret_word_list.remove(letter_guessed)
如果您尝试以下操作:
In [5]: l = [1,2,3,4]
In [6]: print (type(l.remove(1)))
<class 'NoneType'>
如果我使用l = l.remove(1)
,我将其设置为Nonetype的方法,因为它不返回列表,它会改变原始并返回None,而不是更新列表。
追加也是一样的:
`In [7]: print (type(l.append(5)))
<class 'NoneType'>`
`