Function returns None after recursion

前端 未结 1 1579
野趣味
野趣味 2021-01-26 16:35

I have written a function to determine the height of a display, given a width and a format. The function operates recursively, if it cannot find a match for the given width and

1条回答
  •  温柔的废话
    2021-01-26 16:44

    You are not actually returning the recursive call result:

    elif height == width:
        getDisplayDimensions(float(width)-1,FormatX,FormatY)
    

    Add return there:

    elif height == width:
        return getDisplayDimensions(float(width)-1,FormatX,FormatY)
    

    Without the return the outer call just ends and returns the default None instead.

    Demo:

    >>> def getDisplayDimensions(width,FormatX,FormatY):
    ...     Format = float(FormatX)/FormatY
    ...     if FormatX < FormatY:
    ...         return "illegal format."
    ...     for height in range(1,int(width)+1):
    ...         if float(width)/height == float(Format):
    ...             return width,height
    ...             break
    ...         elif height == width:
    ...             return getDisplayDimensions(float(width)-1,FormatX,FormatY)
    ... 
    >>> print getDisplayDimensions(801,16,9)
    (800.0, 450)
    

    0 讨论(0)
提交回复
热议问题