开发者

function returning None (functional programming) [duplicate]

This question already has answers here: Why do I get AttributeError: 'NoneType' object has no attribute 'something'? (11 answers) Closed 6 hours ago.

I'm trying to make an functional function and I want it to return an array (ndarray). I don't know why, but my code is returning None. Here's my code:

def upgrade_array(array:np.ndarray, max_value:int, value:int=1):
    a = array.copy()
    index = value-1
    a[index,:] = value
    #display(a)
    if value==max_value:
        return np.array(a)
    else:
        upgrade_array(array=a, max_value=max_value, value=value+1)
        
a = np.zeros(shape=(10,5))
b = up开发者_C百科grade_array(array=a, max_value=10)
display(b)

I know the logic behind is ok, since I verified it (using display(a)). How can I make it return the a ndarray?


In your else: case, the function does not return a value. Sure, the recursive call might, but the original call will not. You need to return the value up the call chain like so

def upgrade_array(array:np.ndarray, max_value:int, value:int=1):
    a = array.copy()
    index = value-1
    a[index,:] = value
    #display(a)
    if value==max_value:
        return np.array(a)
    else:
        # notice the change here:
        return upgrade_array(array=a, max_value=max_value, value=value+1)
        
a = np.zeros(shape=(10,5))
b = upgrade_array(array=a, max_value=10)
display(b)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜