Список Python NoneType Ошибка

У меня проблема с проектом OpenCourseWare, который я пытаюсь реализовать. Я создаю игру с палачом, и все кажется в порядке, пока я не попытаюсь запустить настоящую функцию для игры.

Я получаю следующую ошибку:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "Game of Hangman/hangman.py", line 118, in play_hangman
    print(print_guessed())
  File "Game of Hangman/hangman.py", line 92, in print_guessed
    if letter in letters_guessed == True:
TypeError: argument of type 'NoneType' is not iterable

Я не могу понять, почему список оценивается как NoneType, даже если он объявлен как пустой список. Я использовал консоль, чтобы попытаться найти ответ, и сказал, что тип NoneType. Может ли кто-нибудь помочь мне, пожалуйста? Я предоставил код в качестве ссылки.

# Name:
# Section: 
# 6.189 Project 1: Hangman template
# hangman_template.py

# Import statements: DO NOT delete these! DO NOT write code above this!
from random import randrange
from string import *

# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
# Import hangman words

WORDLIST_FILENAME = "words.txt"

def load_words():
    """
    Returns a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print "Loading word list from file..."
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r', 0)
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = split(line)
    print "  ", len(wordlist), "words loaded."
    print 'Enter play_hangman() to play a game of hangman!'
    return wordlist

# actually load the dictionary of words and point to it with 
# the words_dict variable so that it can be accessed from anywhere
# in the program
words_dict = load_words()


# Run get_word() within your program to generate a random secret word
# by using a line like this within your program:
# secret_word = get_word()

def get_word():
    """
    Returns a random word from the word list
    """
    word=words_dict[randrange(0,len(words_dict))]
    return word

# end of helper code
# -----------------------------------


# CONSTANTS
MAX_GUESSES = 6

# GLOBAL VARIABLES 
secret_word = get_word()
letters_guessed = []

# From part 3b:
def word_guessed():
    '''
    Returns True if the player has successfully guessed the word,
    and False otherwise.
    '''
    global secret_word
    global letters_guessed
    wordGuessed = False
    ####### YOUR CODE HERE ######
    for letter in secret_word:
        if letter in letters_guessed:
            wordGuessed = True
        else:
            wordGuessed = False
            break
    return wordGuessed


def print_guessed():
    '''
    Prints out the characters you have guessed in the secret word so far
    '''
    global secret_word
    global letters_guessed
    printedWord = []
    ####### YOUR CODE HERE ######
    for letter in secret_word:
        if letter in letters_guessed:
            printedWord.append(letter)
        else:
            printedWord.append("-")
    return printedWord

def play_hangman():
    # Actually play the hangman game
    global secret_word
    global letters_guessed
    # Put the mistakes_made variable here, since you'll only use it in this function
    mistakes_made = 0

    # Update secret_word. Don't uncomment this line until you get to Step 8.
    secret_word  = get_word()

    ####### YOUR CODE HERE ######
    while mistakes_made < MAX_GUESSES or word_guessed() == False:

        print("WORD:")
        userGuess = raw_input("What is your guess?\n").lower()
        if userGuess in secret_word:
            letters_guessed = letters_guessed.append(userGuess)
        else:
            letters_guessed = letters_guessed.append(userGuess)
            mistakes_made += 1
        print(print_guessed())
    if word_guessed() == False:
        print("Sorry but you've run out of guesses...")
    else:
        print("You've correctly guessed the secret word!")
    print("Secret Word: " + secret_word)

Как отказ от ответственности, это не задание в том смысле, что я не зачислен в школу. Я просто парень, который пытается вернуться к программированию и нашел несколько заданий, с которыми можно поиграться.

Заранее спасибо!


person Cipher    schedule 03.02.2013    source источник


Ответы (1)


Похоже, я нашел свой ответ. Проблема оказалась связана с назначением, которое я выполнял с переменной letter_guessed.

Вместо того, чтобы делать:

letters_guessed = letters_guessed.append(userGuess)

Я должен был сделать:

letters_guessed.append(userGuess)
person Cipher    schedule 03.02.2013