Python我明确地返回了None但什么都没有

时间:2018-05-14 03:06:30

标签: python python-3.x

我在基本情况下明确返回print('String to print') ,但doctest告诉它没有

这是我的代码:

None

这是我的错误消息:

def find_triple(ilist):
    """ Find a triple of integers x, y, z in the list ilist such that x + y = z.
    Return the tuple (x, y). If the triple does not exist, return None.

    >>> find_triple([4,5,9]) in [(4,5), (5,4)]
    True
    >>> li = [(30,70), (70,30), (20,50), (50,20), (20,30), (30,20)]
    >>> find_triple([20,40,100,50,30,70]) in li
    True
    >>> find_triple([6,11,7,2,3])
    None
    >>> find_triple([1, 1, 3])
    None
    """
    # define a yield function to reduce the cost of time and space
    def yield_pair(ilist):
        """ enumerate all the two pairs in the list.

        >>> g = yield_pair([4,5,9])
        >>> next(g)
        (4, 5)
        >>> next(g)
        (4, 9)
        >>> next(g)
        (5, 9)
        >>> next(g)
        Traceback (most recent call last):
        ...
        StopIteration
        """
        for i in range(len(ilist) - 1):
            for j in range(i, len(ilist) - 1):
                yield (ilist[i], ilist[j + 1])

    # first turn the ilist into a set, so the `in` operation is much more efficient
    iset = set(ilist)
    g = yield_pair(ilist)
    while True:
        try:
            pair = next(g)
            if sum(pair) in iset:
                return pair
        except StopIteration:
            return None  # ********  problems here ****************
        except:
            return None  # ******** verbose I just try to show that it does not return None *******

3 个答案:

答案 0 :(得分:4)

REPL始终忽略None作为返回值,不打印任何内容。跳过该行的输出或显式打印返回值。

答案 1 :(得分:2)

None值将被忽略。您可以使用以下内容:

""" Find a triple of integers x, y, z in the list ilist such that x + y = z.
Return the tuple (x, y). If the triple does not exist, return None.
>>> find_triple([6,11,7,2,3]) is None
True
>>> find_triple([1, 1, 3]) is None
True
"""

答案 2 :(得分:1)

Shells永远不会显示None结果。但是“根本没有输出”也是doctest可以检查的结果。所以不是这一部分:

>>> find_triple([6,11,7,2,3])
None
>>> find_triple([1, 1, 3])
None
"""

你可以删除“无”行:

>>> find_triple([6,11,7,2,3])
>>> find_triple([1, 1, 3])
"""

如果返回doctest,则None会抱怨。或者您可以明确打印结果:

>>> print(find_triple([6,11,7,2,3]))
None
>>> print(find_triple([1, 1, 3]))
None
"""

或者,正如已经建议的那样,您可以点击is None并显示您希望获得True结果。或者......

哪一个最好?无论找到哪种方式都是最清楚的。我会以上面的第一种方式完成它,但后来我从未期望None显示为开头; - )