NoneType函数如何工作?

时间:2017-02-06 22:10:01

标签: python function python-3.x

为了为游戏创建update_score函数,我正在开发一个返回NoneType的函数。我在Python 3中搜索有关此类函数的一些信息,据我所知,我应该尝试创建它而不打印,但返回NoneType是什么意思?

我尝试使用名为word_score的其他函数来编写此函数,这似乎工作正常,但我陷入了update_score函数。

def word_score(word):
    """ (str) -> int

    Return the point value the word earns.

    Word length: < 3: 0 points
                 3-6: 1 point per character for all characters in word
                 7-9: 2 points per character for all characters in word
                 10+: 3 points per character for all characters in word

    >>> word_score('DRUDGERY')
    16
    >>> word_score('PEN')
    3
    >>> word_score('GRANDMOTHER')
    33
    """
    if len(word) < 3:
        return 0
    elif len(word) in range(3,7):
        return len(word)
    elif len(word) in range(7, 10):
        return len(word)* 2
    elif len(word) >= 10:
        return len(word) * 3



    return word_score


def update_score(player_info, word):
    """ ([str, int] list, str) -> NoneType

    player_info is a list with the player's name and score. Update player_info
    by adding the point value word earns to the player's score.

    >>> update_score(['Jonathan', 4], 'ANT')
    """

    return update_score(['player_info', word_score], 'word')

你觉得这个有什么奇怪的吗?

2 个答案:

答案 0 :(得分:1)

update_score总是自称,所以永远不会回来。

答案 1 :(得分:0)

NoneType函数是一个不会显式返回任何内容的函数,或者一个函数在终止时显式返回None的函数。一个重要的方面是函数返回。问题代码中的update_score()无条件地调用自身,从而创建一个无限循环,直到停止整个脚本的异常发生。

所以你不想这样做。这是update_score()的修改版本,而只是更新传递的列表中的值,就地,然后返回它。因为list s是可变序列,所以返回它(或其他任何东西)是非常必要的 - 因此你可能不需要我最后的return player_info(从技术上来说,它是保持它的是NoneType功能)。

请注意,我还优化了word_score()函数。

def word_score(word):
    """ (str) -> int

    Return the point value the word earns.

    Word length: < 3: 0 points
                 3-6: 1 point per character for all characters in word
                 7-9: 2 points per character for all characters in word
                 10+: 3 points per character for all characters in word

    >>> word_score('DRUDGERY')
    16
    >>> word_score('PEN')
    3
    >>> word_score('GRANDMOTHER')
    33
    """
    word_len = len(word)
    if word_len < 3:
        return 0
    elif word_len <= 6:
        return word_len
    elif word_len <= 9:
        return word_len * 2
    else: # word_len >= 10
        return word_len * 3

def update_score(player_info, word):
    """ ([str, int] list, str) -> [str, int] list

    player_info is a list with the player's name and score. Update player_info
    by adding the point value word earns to the player's score.

    >>> update_score(['Jonathan', 4], 'ANT')
    ['Jonathan', 7]
    """
    player_info[1] += word_score(word)
    return player_info

print(update_score(['Jonathan', 4], 'ANT'))  # -> ['Jonathan', 7]