TypeError: argument of type 'NoneType' is not iterable

前端 未结 2 941
攒了一身酷
攒了一身酷 2020-12-28 11:01

I am making a Hangman game in Python. In the game, one python file has a function that selects a random string from an array and stores it in a variable. That variable is th

2条回答
  •  天涯浪人
    2020-12-28 11:08

    If a function does not return anything, e.g.:

    def test():
        pass
    

    it has an implicit return value of None.

    Thus, as your pick* methods do not return anything, e.g.:

    def pickEasy():
        word = random.choice(easyWords)
        word = str(word)
        for i in range(1, len(word) + 1):
            wordCount.append("_")
    

    the lines that call them, e.g.:

    word = pickEasy()
    

    set word to None, so wordInput in getInput is None. This means that:

    if guess in wordInput:
    

    is the equivalent of:

    if guess in None:
    

    and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

    The fix is to add the return type:

    def pickEasy():
        word = random.choice(easyWords)
        word = str(word)
        for i in range(1, len(word) + 1):
            wordCount.append("_")
        return word
    

提交回复
热议问题